lua-users home
lua-l archive

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


> 
> It's going the other way that I have trouble. I put values on the lua 
> stack from C with lua_push(whatever), but how do I get at them from my lua 
> script when it is run from within the C program?  I'm sort of expecting
> something like perl's "$arg1=shift($_)"

It's much more graceful than that!

You push the items you want to return onto the stack, and then return 
(from your C function) the number of items you are returning (remember 
that Lua functions can return variable numbers of variably-typed results).

Imagine a function which computes a number. It returns the number (if the 
computation worked) or else nil and a error string (if it didn't). So 
you'd call the thing from Lua like this:

  n, e = myfunc()
  if not n then
    --reason in e
  else
    --result in n; e will be nil
  end

To deal with this, you just do this:

  if (computation_worked) {
    lua_pushnumber(result);
    return 1;
  } else {
    lua_pushnil(L);
    lua_pushstring(L,"error");
    return 2;
  }


> BTW, I'm using "lua_dofile" from C to handle my lua script.  I'd really 
> like to split this into something that loads the lua file and then 
> something that calls functions from that lua file later.  

Use lua_call(). See 3.14 of the Lua 5.0 Reference Manual. You can call
any Lua function with any arguments. The Lua invocation implicit in 
your original lua_dofile() should be used to initialise the Lua module
you are loading. There is a great chapter in Programming in Lua (PIL)
on the topic of organising modules. (Chapter 15 -- Packages.)