Skip to main content
gamedev.net
🔒 Locked

Changing Lua function metatable

Started by tcsavage 4 replies 3.1k views
Original Post
tcsavage
tcsavage
I have found myself wanting to override a function's __index and __newindex metamethods. The reason for this is I have a simple C function to expose data to Lua and set a global name (or table index) for it. This means that I can print a C variable myvar in Lua using print(myvar) and set it using myvar(value). I would like to re-wire __index and __newindex to make this more like print(myvar) and myvar=value.

Is this even possible? I have tried using the C API and the debug library without success.
dmail
dmail
Functions in Lua do not have a metatable which you can alter on a per instance basis, so what you are trying to achieve with metamethods is not possible.
What is "myvar"? Table, function, other value type?
tcsavage
tcsavage
OK, i'll have to find another way to do this.

myvar in this instance is a function created using lua_pushcclosure.
dmail
dmail
Quote:
Original post by tcsavage
OK, i'll have to find another way to do this.

To be honest I am not clear what it is you want to do.
Quote:

myvar in this instance is a function created using lua_pushcclosure.

So in the following what is it that you are trying to do
myvar=value

Are you trying to use syntactic sugar via the assignment operator to supply an argument to the function?

tcsavage
tcsavage
Yeah. Essentially I have pushed functions from the C API to access data in C land. A call to myvar() will return the data, myvar(5) will set the data to equal 5.

My aim (as you suspected) was to essentially map myvar() to act like a value rather than a function.
m_switch
m_switch
See:

ObjectProperties

Do note that these techniques have varying degrees of performance implications.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.