Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting C properties from Lua

Tags:

c++

c

lua

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?

like image 262
Dan Avatar asked Oct 31 '13 08:10

Dan


1 Answers

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.

like image 103
Hampus Nilsson Avatar answered Oct 17 '22 16:10

Hampus Nilsson