diff --git a/docs/Lua API.rst b/docs/Lua API.rst index 4c7163623..2cfaff350 100644 --- a/docs/Lua API.rst +++ b/docs/Lua API.rst @@ -158,7 +158,9 @@ that don't fit any of the other reference types. Such references can only appear as a value of a pointer field, or as a result of calling the ``_field()`` method. -They behave as structs with one field ``value`` of the right type. +They behave as structs with a ``value`` field of the right type. If the +object's XML definition has a ``ref-target`` attribute, they will also have +a read-only ``ref_target`` field set to the corresponding type object. To make working with numeric buffers easier, they also allow numeric indices. Note that other than excluding negative values diff --git a/test/main.lua b/test/main.lua index 46a91e1ca..83a35d165 100644 --- a/test/main.lua +++ b/test/main.lua @@ -69,6 +69,19 @@ function expect.error(func, ...) return true end end +function expect.error_match(func, matcher, ...) + local ok, err = pcall(func, ...) + if ok then + return false, 'no error raised by function call' + elseif type(matcher) == 'string' then + if not tostring(err):match(matcher) then + return false, ('error "%s" did not match "%s"'):format(err, matcher) + end + elseif not matcher(err) then + return false, ('error "%s" did not satisfy matcher'):format(err) + end + return true +end function expect.pairs_contains(table, key, comment) for k, v in pairs(table) do if k == key then diff --git a/test/structures/ref_target.lua b/test/structures/ref_target.lua new file mode 100644 index 000000000..05818ee06 --- /dev/null +++ b/test/structures/ref_target.lua @@ -0,0 +1,35 @@ +function test.get() + dfhack.with_temp_object(df.unit:new(), function(unit) + expect.eq(unit:_field('hist_figure_id').ref_target, df.historical_figure) + end) +end + +function test.get_nil() + dfhack.with_temp_object(df.coord:new(), function(coord) + expect.nil_(coord:_field('x').ref_target) + end) +end + +function test.get_non_primitive() + dfhack.with_temp_object(df.unit:new(), function(unit) + expect.error_match(function() + return unit:_field('status').ref_target + end, 'not found') + end) +end + +function test.set() + dfhack.with_temp_object(df.unit:new(), function(unit) + expect.error_match(function() + unit:_field('hist_figure_id').ref_target = df.coord + end, 'builtin property or method') + end) +end + +function test.set_non_primitive() + dfhack.with_temp_object(df.unit:new(), function(unit) + expect.error_match(function() + unit:_field('status').ref_target = df.coord + end, 'not found') + end) +end