How do I eval a string and get its results on the stack?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

How do I eval a string and get its results on the stack?

Sam Roberts-2
I have a debug console in my app, it accepts a string, evaluates it, and I want
to display back to the console user the results of evaluating the expression.

For example, given

  function two() return 2 end

I would like to be able to do in C:

  Lua_EvalString(lua, "two()");

and then see 2 on the top of the lua stack.

After calling lua_pcall() I never see anything on the stack (unless an error
occurred, in which case I see the error string and can display that).

My code:

        // Note - static functions cut from lua.c, the lua interpreter source.
        static int docall (lua_State* L, int status)
        {
          if (status == 0)
                  status = lua_pcall(L, 0, LUA_MULTRET, 0 /* errhandler */);
          return status;
        }

        static int dostring (lua_State* L, const char *s, const char *name)
        {
          return docall(L, luaL_loadbuffer(L, s, CStr_GetLength((char*)s), name));
        }

        FCHR32 Lua_EvalString(lua_State* Interpreter, const char* chunk)
        {
                int result = dostring(Interpreter, chunk, "=<eval>");

                if(result)
                {
                        return 'L000' + result;
                }

                return ERR_NONE;
        }

Does anybody have a suggestion as to what I'm doing wrong?

Thanks,
Sam

Reply | Threaded
Open this post in threaded view
|

Re: How do I eval a string and get its results on the stack?

Luiz Henrique de Figueiredo
> I would like to be able to do in C:
>
>   Lua_EvalString(lua, "two()");
>
> and then see 2 on the top of the lua stack.

Try
   Lua_EvalString(lua, "return two()");
Reply | Threaded
Open this post in threaded view
|

Re: How do I eval a string and get its results on the stack?

Sam Roberts-2
On Fri, Apr 07, 2006 at 03:51:26PM -0300, Luiz Henrique de Figueiredo wrote:
> > I would like to be able to do in C:
> >
> >   Lua_EvalString(lua, "two()");
> >
> > and then see 2 on the top of the lua stack.
>
> Try
>    Lua_EvalString(lua, "return two()");

Thanks, I'm so used to every expression resulting in a value, that never
occurred to me, works wonderfully.

Sam