[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Cannot call lua function from C application
- From: Sam Roberts <sroberts@...>
- Date: Mon, 31 Jul 2006 10:25:16 -0700
On Tue, Aug 01, 2006 at 12:55:30AM +0800, Yang Fan wrote:
> Hi all,
> I'm new in Lua.I'm trying embedding the interpreter into my C++
> application.I write a script file like this:
> function main (data)
> str = data
> while i'm using C++ code to call this "main" function, but failed:(
> if (luaL_loadfile(L, pszFileName))
> trace1(("Cannot run lua file: %s", lua_tostring(L,-1)));
The code is loaded, but not yet run. When the code runs, it will define
the function. So, you have to do a lua_pcall() after the load.
> /* push functions and arguments */
> lua_getglobal(L, "main"); /* function to be called */
> lua_pushlstring(L, m_data.c_str(), m_data.size());
> /* do the call (1 arguments, 0 result) */
> if (lua_pcall(L, 0, 0, 0) != 0)
This is the number of function args.
What you have is:
 a chunk of code "function main() .... "
 result of lua_getglobal("main"), I bet that this is nil!
 a string
You then make a call with zero args, so the top of the stack is the
"function" being called, but it is a string! That is why you have
"attempt to call a string value".
I suggest you write a function that will go through the stack and print
all the values, that would help you understand better what is happening.
And lua is a bit subtle to understand, try reading the docs, and also I
suggest reading the code for the lua interpreter, lua.c, it is easy to
read, educational, and an example of loading strings and evaluating
> trace1(( "Error running function \"main\": %s",
> lua_tostring(L, -1)));
> error msg showed:Error running function "main": attempt to call a string
> i really don't know what's wrong with my code, need your help! thanks!!
> And sorry for my pool english:(