I have a few values in C that I would like to update from Lua and I've written my own binding functions, but I want to know if something is possible.
I want to be able to do this
myNamespace.myValue = 10
and have it do the same thing as this
myNamespace.setMyValue(10)
Possible? Just curious mostly. It's just cleaner to assign/read a value directly instead of calling a get/set function. Can Lua do any auto-translation like that?
This is certainly possible. You can overload the __newindex
metamethod to translate myValue to setMyValue
and then call that on the table. An 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 value to Hello".
You might want to overload __index to do the same but with getMyValue
as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With