Skip to main content
GameDev.net gamedev.net
🔒 Locked

struct in lua

Started by luasitdown Dec 6, 2005 at 11:21 AM 2 replies 5.9k views
Original Post
luasitdown
luasitdown
table is only struct in table. but it is simple. How to describe the struct below: struct A { int id; string name; string parent; string type; } table A = {} .........//still no solution
NoodleCower
NoodleCower
Well, I can't say for sure that this will work, but say you have a function that wants to push your struct A onto the Lua stack as a table, this is how I'd go about it.

int lua_GetA( lua_State* state ){	A* a = getA( "..whatever you're gonna do to get the value/pointer/whatever you want.." );	// create a new table	lua_newtable( state );	// push the ID	lua_pushstring(state, "id");	lua_pushnumber(state, a->id);	// set the table	lua_settable( state, -3 );	// rinse and repeat..	// push the name	lua_pushstring(state, "name");	lua_pushstring(state, a->name.c_str());	lua_settable( state, -3 );	// push the parent	lua_pushstring(state, "parent");	lua_pushstring(state, a->parent.c_str());	lua_settable( state, -3 );	// push the type	lua_pushstring(state, "type");	lua_pushstring(state, a->type.c_str());	lua_settable( state, -3 );	// return the table	return 1;}


This way, you can do something akin to this in Lua:

myA = GetA( "I don't know, some value used to tell what A you want?" )SetAPosition( myA.id, 24, 32 )SetAAwesomeness( myA.id, 2000000000 ) -- two billion!


Hope that helps.
__ODIN__
__ODIN__
Quote:
Original post by luasitdown
table is only struct in table. but it is simple.
How to describe the struct below:

struct A
{
int id;
string name;
string parent;
string type;
}

table A = {}
.........//still no solution


I take it what you wanted to do was really to create a 'struct' inside LUA?
LUA doesn't use, or really need, structs, since the table is associative.

local A = {};   -- A is a tableA['id'] = 230;   --A['name'] = 'foo';A['parent'] = B;A['type'] = 'big_scary_monster';


This would be equivalent to a C style structure. Also, since both tables and functions are first-class variables in LUA, you can do cool stuff like this.

function Gloat()    print('I'm gloating') endA['on_kill'] = Gloat;



Allan
Flimflam
Flimflam
Can also write a helper function for creating them.
function MakeStruct(id, name, parent, type)  local tmp = {}  tmp['id'] = id;  tmp['name'] = name;  tmp['parent'] = parent;  tmp['type'] = type;  return tmp;endlocal X = MakeStruct( 20, "my_name", "dads_name", "wimp" );print( X['id'] );

You can't actually define a struct in Lua. you have to basicly just create a basic table and copy from it each time you want an object iwth that structure.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.