2
votes

I am implementing a metatable in C with Lua's C API. I wonder whether the __newindex method should report success or failure by returning a value, or if this should be handled by using errors.

It seems that in the context of __index with return 0 indicates a failure to look up a value, I wonder whether there is a similar construct in __newindex that avoids ignoring or manual error throwing

2

2 Answers

2
votes

Lua expects no return value from a newindex metamethod. See http://www.lua.org/manual/5.2/manual.html#2.4.

If your failure is fatal, just raise an error inside your metamethod.

1
votes

Returning a value from C to Lua indicates the number of results pushed onto the stack. When returning 0 any assignment made in Lua using the result of the method will be nil. When you return 0 in the context of __index you are simply indicating that no value has been pushed onto the stack. You could get the same result by pushing nil and returning 1.

Similarly in the context of __newindex your return value from C indicates how many results you have pushed onto the stack.