Ok, so I've been working with Lua for a while now, and have got myself stumped at reworking the engine abit. Hoping someone here might have the knowledge to help point in the right direction. We have started to try and work with metatables to be able to pull direct data from C structures, and to modify the C structures from within lua as well. My big stump is, i've never used metatables before and can't find exactly how to set one up in the fashion I need.
What we seek is the usability to attach a userdatum to a metatable along with the methods for the structure, for example what we want to be able to do:
ch.hit = 300 send_char(ch.name .. " Your hit poitns have been modified too " .. ch.hit, ch)
if that makes sense to anyone, never been too good at explaining things ;) Will help clarify if it dosent make sense.
Per the Lua 5.1 reference manual, "Userdata values cannot be created or modified in Lua, only through the C API. This guarantees the integrity of data owned by the host program."
Beyond that, I'm pretty sure you can't define a metamethod for '=', although there is one for newindex (e.g., "table[key] = value"). So, you're going to need to define a metamethod to replace newindex that takes the key and value args and passes them to a C function. You'll have to actually modify your ch table/struct in the C function.
That C function is probably going to be somewhat gnarly, as you will probably have to map strings to each member of the struct. You could use integers alternatively, but I don't see you getting around having to build out a map.
- first, create the metatable: this can happen in C or Lua, it doesn't really matter. Stick it in some place you can easily retrieve it from later. (E.g., the registry if you created it from C; if you created it from Lua, you can use a global variable, or return it and have C put it in the registry.)
In C, now: - put the metatable on the stack. (retrieve it according to how you created it) - create your userdatum object. - associate the metatable with the userdatum. (there's an API call that does just this)
I'll have a fairly extensive example of this published at some point, as soon as I finish cleaning up my code for publishing…
We got it working :) after a few days of Hack and Slash, and some help from Kiasyn, thought not perfected, it does work, and DH, I would love to see yer extensive examples to furhter our development to see if we missed anything important that we didnt see already.