[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Best way to share "structs" between C and Lua
- From: Alex Bilyk <nebula-crl-2688@...>
- Date: Thu, 16 Jan 2003 23:57:41 -0800
I would use a bunch of user data types for each simple C type and
associate all operations you normally do with variables using
metatables. The assignment would either use "call" event or "index"
event for some predefined name, say, "set". Such userdata would hold an
address of a single C variable.Basically the C interface would look
somthing like this
struct cMonster_tag
{
int mHealth;
char* mName;
} cMonster;
// creates new game object and sets it as light user data into the table
// bind all functions
// structure fields by address as user data
int CreateNewTable_Monster(L);
// takes the object type string
int CreateNewObject(L); // would call functions like
CreateNewTable_Monster(L); internally
// creates userdata for pC and sets a metatable for it to handle all
events (+, *, /, <, index for "set", etc.)
//
void Bind<C-type>Var(C-type* pC, const char* name, int table_index);
CreateNewTable_Monster(L); would call Bind<C-type>Var internally for all
it's data members that you would wanto access from Lua.
For instance,
BindCIntVar(&monster->mHealth, "health", -1);
BindCStringVar(&monster->mName, "name", -1);
And then you would be able to do everything transparently in Lua except
assignments, which would use "set" method
monster.health.set(0).
or a "call" event and function call syntax
monster.health(0)
I think this kind of binding would have the lowest runtime overhead and
can be used for any C-var elsewhere in your code.
Overall, in Lua your would say something like this
monster = CreateNewObject("monster")
monster.health(100)
monster.name("Mean Killer Bee")
or even
monster = NewObject("monster", {health = 100, name = "Mean Killer Bee"})
...
monster.health(2)
if (monster.health < 6)
then
monster:die()
end
jose_marin2 wrote:
Hi!
I'm looking for a good (fast!) way of sharing the C structs of my
game with the Lua code.
For example, in C I have the struct:
struct MonsterInfo{
char name[MAX_NAME];
int health;
};
and in Lua I could have 2 functions:
------------------------------------
function NewMonster(name, health)
local tbl = {}
tbl.name = name;
tbl.health = health;
function tbl:Die()
...
end
return tbl
end
function Damage(ent, amount)
ent.health = ent.healt - amount
if ent.health <= 0 then
ent:Die()
end
end
------------------------------------
The problem is how to (fast and easy) keep in the same data (struct)
in Lua and in C.