Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Report error at source of __newindex call rather than inside __newindex function

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?

like image 929
Alex Avatar asked Dec 08 '13 07:12

Alex


1 Answers

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
like image 81
Julien Desgats Avatar answered Sep 29 '22 06:09

Julien Desgats