lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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)
>    ConsoleOutput(data)
>    str = data
> end
> 
> 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)
                          ^nargs
This is the number of function args.

What you have is:

  [1] a chunk of code "function main() .... "
  [2] result of lua_getglobal("main"), I bet that this is nil!
  [3] 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
them.

Cheers,
Sam


>        {
>            trace1(( "Error running function \"main\": %s",
> lua_tostring(L, -1)));
>        }
> 
> error msg showed:Error running function "main": attempt to call a string
> value
> 
> i really don't know what's wrong with my code, need your help! thanks!!
> And sorry for my pool english:(