2

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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
TravisG
  • 2,373
  • 2
  • 30
  • 47
  • Set up the global table to have a `newindex` metamethod that pushes the changes to your `int foo`, and an `index` metamethod that retrieves changes to `int foo`. – Mankarse Jun 21 '14 at 20:32

1 Answers1

3

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Can I set this up to preserve the actual syntax I'm looking for (foo = 5)? Or would I have to create a global table (let's call it "basicGlobals", and do e.g.: basicGlobals.foo = 5 ? – TravisG Jun 22 '14 at 13:55
  • You can preserve the standard syntax for the Lua side, the C side (and the notifier-function at `__newindex`) though need to mind where you actually store the data. – Deduplicator Jun 22 '14 at 14:39