Timur Kukharskiy
Timur Kukharskiy

Reputation: 303

Lua in c++ strange behavior that i can`t understand?

i have a question about this simple code of LUA script that is used in C++.

Main.cpp
#include <iostream>
using namespace std;
extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int main()
{
    lua_State *L=luaL_newstate();
    luaL_openlibs(L);
    luaL_loadfile(L,"script.lua");
    lua_call(L,0,1);
    int n;
    n=lua_tonumber(L,-1);  // Can be changed to 0 and i gain the same result as -1
    cout<<n<<endl;
    lua_close(L);
    cout<<"test"<<endl;
    return 0;
}

script.lua
print("Hello world")
return 10

Program is working correctly and return 10 to console but, the question is why when i change lua_tonumber(L,-1) -1 to 0 it still returns 10? It seems that i have two 10 in the stack one with index 0 and other with index -1. But why?

Upvotes: 2

Views: 156

Answers (1)

cubuspl42
cubuspl42

Reputation: 8360

From Lua documentation:

A positive index represents an absolute stack position (starting at 1); a negative index represents an offset relative to the top of the stack.

0 index is unallowed in Lua and the behavior is undefined (probably it just changes 0 to 1, but you shouldn't rely on that).

Upvotes: 3

Related Questions