Hardware Design: SIE
Sign in or create your account | Project List | Help
Hardware Design: SIE Git Source Tree
Root/
| 1 | Examples from http://www.wellho.net/mouth/1844_Calling-functions-in-C-from-your-Lua-script-a-first-HowTo.html |
| 2 | |
| 3 | If you may with to pass a table from your Lua script into a C function, so that the C function can make use of a value from the table code like this: |
| 4 | |
| 5 | stuff = {hotel = 48, hq = 404, town = 1} |
| 6 | .... |
| 7 | summat = extratasks.dothis(stuff) |
| 8 | |
| 9 | This isn't as easy as just passing a value, since the size of a table can vary, and Lua's dynamic memory allocation doesn't sit well, in a simple interface, with C's static model. The "trick" is to tackle it within the C code by using function calls to get (and if necessary) reset values from the table - with the data required by those function calls being processed via the Lua stack. |
| 10 | |
| 11 | /* Looking up based on the key */ |
| 12 | /* Add key we're interested in to the stack*/ |
| 13 | lua_pushstring(L,"hq"); |
| 14 | /* Have Lua functions look up the keyed value */ |
| 15 | lua_gettable(L, -2 ); |
| 16 | /* Extract the result which is on the stack */ |
| 17 | double workon = lua_tonumber(L,-1); |
| 18 | /* Tidy up the stack - get rid of the extra we added*/ |
| 19 | lua_pop(L,1); |
| 20 | |
| 21 | That code retrieves the "hq" value from the table that's been passed in (called stuff in my Lua example above) and stores it into a C variable called workon ... objective achieved! |
| 22 | |
| 23 |
Branches:
master
