Help with lua problem

Started by
1 comment, last by Programmer16 20 years ago
I'm just starting to learn lua using the tutorials from tonyandpaige.com. I have a simple function that adds two numbers, but it doesn't work. I've copied the text almost exactly, but it doesn't work:

//##################################################################################

// Lua Test

//##################################################################################

#include <iostream.h>
#include <stdio.h>

extern "C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

//##################################################################################

// Global variables

//##################################################################################

lua_State* g_pLuaState = NULL;

//##################################################################################

// Function prototypes

//##################################################################################

int luaadd(int x, int y);

//##################################################################################

// WinMain()

//##################################################################################

int main()
{
	int iSum = 0;
	g_pLuaState = lua_open();
	lua_baselibopen(g_pLuaState);
	lua_dofile(g_pLuaState, "add.lua");

	iSum = luaadd(10, 15);
	cout<<"The sum of 10 and 15 is "<<iSum<<endl;
	lua_close(g_pLuaState);
	return 0;
}

int luaadd(int x, int y)
{
	int iSum = 0;
	lua_getglobal(g_pLuaState, "add");
	lua_pushnumber(g_pLuaState, x);
	lua_pushnumber(g_pLuaState, y);
	lua_call(g_pLuaState, 2, 1);
	iSum = (int)lua_tonumber(g_pLuaState, 1);
	lua_pop(g_pLuaState, 1);
	return iSum;
}

And my add.lua:
-- add two numbers
print("Hello World!")

function add(x, y)
	return x + y
end
The print("Hello World!") line works, but that's it. Ok, I downloaded his and the problem is that you have to call lua_tonumber(g_pLuaState, -1) instead of 1, but why? /* I use DirectX 9 and C++ (Microsoft Visual C++ 6.0 Professional edition) */ [edited by - Programmer16 on April 24, 2004 1:08:14 AM]
Advertisement
The problem is that lua_baselibopen leaves stuff on the stack after it runs, and luaadd is not expecting that. Put a lua_settop(g_pLuaState, 0) after the lua_baselibopen line, and that should fix it. For more info on stack indices, look in the manual.

"Sneftel is correct, if rather vulgar." --Flarelocke
Alright, I''ll have to read the manual. Thanks!

/*
I use DirectX 9 and C++ (Microsoft Visual C++ 6.0 Professional edition)
*/

This topic is closed to new replies.

Advertisement