pugnator
pugnator

Reputation: 715

Lua boolean can't be compared like a numbers?

I use Lua 5.3 C API

I use Lua C API to communicate with the script modeling device. Lua script describes the behavior of the device. Here is C function called from Lua

static int
lua_get_pin_bool ( lua_State* L )
{
    lua_Number argnum = lua_gettop ( L );
    if ( 1 > argnum )
    {
        out_error ( "Function %s expects 1 arguments got %d\n", __PRETTY_FUNCTION__, argnum );
        return 0;
    }
    int32_t pin_num = lua_tonumber ( L, -1 );
    bool state = get_pin_bool ( device_pins[pin_num]);
    if ( -1 == state )
    {       
        lua_pushnil(L);
        return 1;
    }
    lua_pushboolean ( L,  state);
    return 1;
}

And corresponding Lua function that utilizes it (get_pin_bool calls lua_get_pin_bool)

function device_simulate()
    for i = 0, 14 do
        if 1 == get_pin_bool(_G["A"..i]) then
            ADDRESS = set_bit(ADDRESS, i)
        else
            ADDRESS = clear_bit(ADDRESS, i)
        end
    end
    for i = 0, 7 do
        set_pin_bool(_G["D"..i], get_bit(string.byte(rom, ADDRESS), i))
    end
end

In Lua get_pin_bool is never returned in fact. lua_pushboolean returns and C code works correct. If I change it to lua_pushnumber all works correct. In fact it doesn't affect the logic of library but I can't understand why it corrupts the Lua VM. I doublechecked state variable in C and it always 0 or 1.

Upvotes: 2

Views: 1478

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80921

There is a problem with your script's logic here

if 1 == get_pin_bool(_G["A"..i]) then

lua is not C. A boolean value is not equal to the number one (or any other number).

Upvotes: 3

Related Questions