lua-users home
lua-l archive

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


On 30 April 2014 15:07, steve donovan <steve.j.donovan@gmail.com> wrote:
>
> On Wed, Apr 30, 2014 at 2:29 PM, Thijs Schreijer
> <thijs@thijsschreijer.nl> wrote:
> > On what line do you get that? On my system it works as expected. But because you do it embedded; have you opened the standard libraries? I suspect that the 'print' function is not available.
>

I'm not using print in my Lua test files, I'm just making my functions
do something else trivial like:

file_y.lua
=======
local M = {}

M.func_y = function(x)
    return x*2
end

return M

file_x.lua
=======
local file_y = require("file_y")

func_x = function()
    x = file_y.func_y(4)
    --print("func_x was called")
end

func_x()

>
>
> But is the error coming from the script?  Usually you'd do something
> like (error checking omitted)
>
> lua_getglobal(L,"fun_x");
> lua_pcall(L,0,0,0);


Here's what I do:

===============
extract from c code
===============
luaMainSt = luaL_newstate();

if ( luaMainSt ) {
    luaL_openlibs( luaMainSt );

    luaL_loadfilex( luaMainSt, LUA_X_FILE, "bt" );
    luaL_loadfilex( luaMainSt, LUA_Y_FILE, "bt" );

    setLuaPath(luaMainSt);   // See below

    lua_getglobal( luaMainSt, "func_x" );

    lua_error = lua_pcall( luaMainSt, 0, 0, 0 );

    if (lua_error) {
        memset( lua_msg_buff, 0, LUA_ERROR_MSG_LEN+1 );
        memcpy( lua_msg_buff, lua_tostring( luaMainSt, -1 ),
LUA_ERROR_MSG_LEN );
        // --> Here is when I see that the error is:
        // "attempt to call a nil value"
        lua_pop( luaMainSt, 1 );
    }
}


int setLuaPath( lua_State* L)
{
 const char* pCh;
 char curr_path[256];
 char special_path[] = ";0:?.lua;0:\?.lua;0:/?.lua";

 memset(curr_path, 0, 256);

 lua_getglobal( L,"package" );

lua_getfield( L, -1, "path" ); // get field "path" from table at top
of stack (-1)

pCh = lua_tostring( L, -1 ); // grab path string from top of stack

strcpy(curr_path, pCh);

strcat(curr_path, special_path);

lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5

lua_pushstring( L, curr_path ); // push the new one

lua_setfield( L, -2, "path" ); // set the field "path" in table at -2
with value at top of stack

lua_pop( L, 1 ); // get rid of package table from top of stack

return 0; // all done!
}


What am I missing?
I.

--