Jump to content
  • Advertisement
Sign in to follow this  
BradDaBug

Passing an array from C to Lua

This topic is 4872 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a way to send an array from C to a Lua script? I want to send a vector to a Lua script, and what I've been doing so far is using userdata to pass a pointer to a vector object, and then the scripts get each element with functions like GetX(), GetY(), GetZ(), but that's pretty lame. I'd rather just pack each element up into an array and let the script access it as an array.

Share this post


Link to post
Share on other sites
Advertisement
OK, figured it out on my own.

void PushFloatArray(float *array, int size)
{
lua_newtable(state);

for (int i = 0; i < size; i++)
{
lua_pushnumber(state, i); // push the index
lua_pushnumber(state, array); // push the value at 'i'

// the table is now at -3 on the stack. This tells Lua
// to put "stack[-1]" at "stack[-2]" and pop them off,
// leaving the table at the top of the stack
lua_settable(state, -3);
}
}

Share this post


Link to post
Share on other sites
I'm almost positive you want to add a little more to that.
After you push all the table cells you need to 'close' the table with the number of cells the table contains (I may be using the word 'cells' where it should in fact be 'rows').


// open/create table
lua_newtable(state);

// new cell
lua_pushnumber(state, i); // note, you can replace this with a string if you want to access table cells by 'key'
lua_pushnumber(state, value);
lua_rawset(state, -3); // insert the new cell (and pop index/value off stack)

// close table
lua_pushliteral(state, "n");
lua_pushnumber(lua, size); // number of cells
lua_rawset(state, -3);


I'm not sure what the difference between 'lua_settable' and 'lua_rawset' is, but lua_rawset() is what I use. I'm sure it's no biggie, but still, does anybody know what the deal is?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!