Reputation: 69
I want to call c functions from lua to change variables defined in C, but I don't want the lua "user" to realize they are functions.
For example, consider an integer and an array created in c:
int c_level = 0;
int c_map[4] = {0,0,0,0};
Now the program creates a Lua state and runs this:
set_level(2) --c_level = 2
set_tile(1,23) --c_map[0] = 23
I want them to look like this in the lua script:
L_level = 2
L_map[1] = 23
So, L_level and L_map would be functions defined in C.
L_level's argument would be "2".
L_map's arguments are "1" and "23".
Is that possible?.
I can get the lua variables using getglobal, but I wanted to know if I can create some lua functions that look like the ones I showed.
Thanks.
Upvotes: 4
Views: 1159
Reputation: 18420
When you set
L_level = 2
you really index the global table _G
with the key L_level
and set it to 2
. What you can do is to set a meta-table for _G
and set the function __newindex
to a function, that checks if the key is L_level
or L_map
and handles these cases differently.
This function can be directly a C-function or a Lua-function, that checks the key and calls a c-function if the name matches one of your tracked names, for example like
setmetatable(_G, {
__newindex = function (_, k, v)
if (k == "L_level") then do_setlevel(v)
elseif (k == "L_map") then do_setmap(v)
else rawset(_G, k, v)
endif
end
})
do_setlevel
and do_setmap
are in this case global c functions. You can of course do all this completely in C, too.
Upvotes: 1