1

I'm trying to return my C++ struct to lua using Swig and I want to have two constructors taking string or double as arguments.

struct MyType
{
    MyType(const std::string & arg)
    {
        std::cout << "string constructor\n";
    }

    MyType(double arg)
    {
        std::cout << "double constructor\n";
    }
}

In Lua running

MyType("3.14")
> double constructor

strInput = "3.14"
print(type(strInput))
> string
MyType(strInput)
> double constructor

What's more it looks like the string is parsed to double. So if I wanted to print argument from double constructor it would be 3.14.

Could there be any implicit conversion to double happening?

Mahashi
  • 119
  • 7
  • Does [this](https://stackoverflow.com/a/12426701/1810087) help? – user1810087 Apr 17 '19 at 13:16
  • @user1810087 nope I've already had it included – Mahashi Apr 17 '19 at 13:37
  • What's more funny when I deleted double constructor it matches numbers as a string. – Mahashi Apr 17 '19 at 13:46
  • I believe the system is using `lua_isnumber` before `lua_isstring`, which eventually invokes `luaV_tonumber_` if the value is not a float. `luaV_tonumber_` tries converting a string to a number if it is convertible, hence it assuming your string should be interpreted as a number. [luaV_tonumber_](https://www.lua.org/source/5.3/lvm.c.html#luaV_tonumber_). This could be remedied if the types were checked explicitly, instead of relying on `lua_isstring` and `lua_isnumber`. – Bas Groothedde May 04 '19 at 12:48
  • I can confirm that `lua_isnumber` is defined first in the [`swig/luatypemaps.swg`](https://github.com/swig/swig/blob/master/Lib/lua/luatypemaps.swg#L20) in the SWIG source code. I'm assuming it checks the typemap in order, meaning all number-like strings are converted to number. – Bas Groothedde May 04 '19 at 12:58
  • This is the expected behaviour. Read [3.4.3 Coercions and Conversions](https://www.lua.org/manual/5.3/manual.html#3.4.3) in the Lua reference manual. There it says: “Lua also converts strings to numbers, whenever a number is expected.” – Henri Menke May 05 '19 at 06:02
  • @HenriMenke I don't agree that this is expected behaviour; the implementation of Lua in Swig causes this. If Swig would have used `lua_type` tests rather than using `lua_isstring` and `lua_isnumber` it would be able to match types in signatures better. – Bas Groothedde May 05 '19 at 22:59

0 Answers0