I have a metatable with the following __newindex
function:
__newindex = function(t, key, value)
set_value(t.sprite_number, key, value)
end
This lets me allow users to set "properties" on my lua objects (there's a corresponding __index
function, but it's not really relevant).
set_value
is a C function. If you try to set the wrong type on a "property," say setting a string value on an integer property, the C code does
luaL_error (l, "property must be a number");
This works fine, except the error reported from lua is
[string "-- init.lua..."]:10: property must be a number
Which is referring to the set_value function call in my __newindex function. This isn't very helpful. I'd like the error to instead point to the place where the wrong value was set, i.e. in the spot where you do
object.property = "expects integer"
Can I accomplish this somehow?
You can use the error function and give the level
parameter:
__newindex = function(t, key, value)
local ok, err = pcall(set_value, t.sprite_number, key, value)
-- level 2 means that the error will be signaled on 2nd stack frame,
-- that is the line at which the key has been set
if not ok then error(err, 2) end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With