Saving values ​​in userdata object from lua

I want to do the following:

object.foo = "bar"

print(object.foo)

where "object" is userdata.

I searched for search queries for a while (using the __newindex and lua_rawset keywords), but I can’t do any examples of what I want it to do.

I want to do this using lua api in c ++

+2
source share
3 answers

We write this in Lua code so that we can quickly experiment with the code.

function create_object()
  -- ## Create new userdatum with a metatable
  local obj = newproxy(true)
  local store = {}
  getmetatable(obj).__index = store
  getmetatable(obj).__newindex = store
  return obj
end

ud = create_object()
ud.a = 10
print(ud.a)
-- prints '10'

If you are working with user data, you probably want to do this using the C API. However, Lua code should clearly indicate which steps are needed. (The function newproxy(..)simply creates dummy user data from Lua.)

+3
source

, ++, lua. (_R) -.

_R.METAVALUES = {}

for key, meta in pairs(_R) do
    meta.__oldindex = meta.__oldindex or meta.__index

    function meta.__index(self, key)
        _R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}
        if _R.METAVALUES[tostring(self)][key] then
            return _R.METAVALUES[tostring(self)][key]
        end
        return meta.__oldindex(self, key)
    end

    function meta.__newindex(self, key, value)

        _R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}

        _R.METAVALUES[tostring(self)][key] = value
    end

    function meta:__gc()
        _R.METAVALUES[tostring(self)] = nil
    end
end

- , . tostring (self) , tostring. ID, Vec3 Ang3, .

+1

You can also use a simple table ...

config = { tooltype1 = "Tool",   
        tooltype2 = "HopperBin",   
        number = 5,
        }   

print(config.tooltype1) --"Tool"   
print(config.tooltype2) --"HopperBin"   
print(config.number) --5
0
source

All Articles