Setting C Properties from Lua

I have several values ​​in C that I would like to update from Lua, and I wrote my own binding functions, but I want to know if something is possible.

I want to be able to do it

myNamespace.myValue = 10 

and let him do the same as this

 myNamespace.setMyValue(10) 

Possible? Just curious mostly. Just simply assign / read the value directly instead of calling the get / set function. Can Lua do any kind of automatic translation?

+6
source share
1 answer

It is certainly possible. You can overload the __newindex __newindex to translate myValue to setMyValue , and then call it in the table. Example:

 local meta = { __newindex = function(t, key, value) local setterName = "set" .. key:sub(0, 1):upper() .. key:sub(2) local setter = t[setterName] if setter == nil then error("Setter " .. setterName .. " does not exist on table") end return setter(t, value) end } local table = { setMyValue = function(self, v) print("Set value to " .. tostring(v)) end } setmetatable(table, meta) table.myValue = "Hello" 

This will print "Set Hello."

You might want to overload __index to do the same, but with getMyValue .

+7
source

Source: https://habr.com/ru/post/957110/


All Articles