Skip to content

Commit

Permalink
lua: Add __tostring to units
Browse files Browse the repository at this point in the history
Makes it easier to test SUFs with wesnoth.get_units{} in the lua console.
  • Loading branch information
jostephd committed Oct 16, 2019
1 parent 942a1d3 commit a67b9d0
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/scripting/lua_unit.cpp
Expand Up @@ -239,6 +239,28 @@ static int impl_unit_equality(lua_State* L)
return 1;
}

/**
* Turns a lua proxy unit to string. (__tostring metamethod)
*/
static int impl_unit_tostring(lua_State* L)
{
const unit& u = luaW_checkunit(L, 1);
std::ostringstream str;

str << "unit: <";
if(!u.id().empty()) {

This comment has been minimized.

Copy link
@ProditorMagnus

ProditorMagnus Oct 16, 2019

Contributor

Is unit id allowed to be empty?

This comment has been minimized.

Copy link
@jostephd

jostephd Oct 16, 2019

Author Member

Haven't been able to get that to happen. Units usually have an idea such as Mage-5 if WML doesn't assign an explicit one.

str << u.id() << " ";
} else {
str << u.type_id() << " ";
}
// This will say 0,0 (or -999,-999?) for units on the recall list
str << "at (" << u.get_location() << ")";
str << '>';

lua_push(L, str.str());
return 1;
}

/**
* Gets some data on a unit (__index metamethod).
* - Arg 1: full userdata containing the unit id.
Expand Down Expand Up @@ -620,6 +642,8 @@ namespace lua_units {
lua_setfield(L, -2, "__gc");
lua_pushcfunction(L, impl_unit_equality);
lua_setfield(L, -2, "__eq");
lua_pushcfunction(L, impl_unit_tostring);
lua_setfield(L, -2, "__tostring");
lua_pushcfunction(L, impl_unit_get);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, impl_unit_set);
Expand Down

0 comments on commit a67b9d0

Please sign in to comment.