Skip to content

Check range of integral when converting from number #91

@Flamefire

Description

@Flamefire

In Lua numbers are essentially doubles. So the following is valid in lua: foo(-1)

If this is bound to a C++ function void foo(unsigned i) it silently does the wrong thing.

This is caused by the unchecked cast at:

return static_cast<get_type>(lua_type_traits<lua_Number>::get(l, index));

Similar problem for C++ function void bar(int8_t i) called with foo(1000)

Proposed fix:


lua_Number num = lua_type_traits<lua_Number>::get(l, index);
if(num < std::numeric_limits<get_type>::min() || num > std::numeric_limits<get_type>::max())
  throw LuaTypeMismatch();
return static_cast<get_type>(num);

Probably extract the check to a standalone function as it is also required at other places (e.g. opt and for Lua 5.3)

Not sure if this breaks the contract of strictCheckType as it may be possible, that a value passes the check (just from checking types) but fails to be gotten as it is outside the range.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions