Search code examples
lualua-api

Pointer to number


It seems like there's know such thing as a reference to a number/boolean/lightuserdata in Lua. However, what would be the easiest way to set a global in Lua that points to a C++ native type (e.g. float) and have it update automatically when I change the corresponding global in Lua?

int foo = 2;
//imaginary lua function that does what I want
lua_pushnumberpointer(state,&foo)
lua_setglobal(state,"foo")
-- later, in a lua script
foo = 5; 

The last line should automatically update foo on the C++ side. What would be the easiest way to achieve something like this?


Solution

  • Take a look at meta tables, especially the tags __index and __newindex.
    If you set them to suitable functions, you have full control what happens when a new index is set / an unset index is queried.

    That should allow you to do all you asked for.

    It might be advantageous to only set __newindex to a custom function and save the interesting entries in a table set on __index.

    Example handler for __newindex and companion definition of __index.
    Consider implementing it on the native side though, for performance, and because __hidden_notify_world() is most likely native.

    do
      local meta = getmetatable(_ENV) or {}
      setmetatable(_ENV, meta)
      local backing = {}
      _ENV.__index = backing
      function _ENV:__newindex(k, v)
        if backing[k] ~= v then
          backing[k] = v
          __hidden_do_notify_world(k, v)
        end
      end
    end
    

    If you are using Lua < 5.2 (2011), you must use _G instead of _ENV.