lua-users home
lua-l archive

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


Am 09.04.2013 06:40 schröbte Michael Stephens:
Hi all,

Hi!


[...]

C Code:

extern "C" {

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "lobject.h"

lobject.h is an internal header. You probably don't need it (certainly not for the code you posted), and it usually isn't part of lua-dev-packages.

}
#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L,
(n)))

This one already is part of the Lua API and defined the same way. Why did you redefine it?

static int print(lua_State* L);
static int test(lua_State* L);

static const struct luaL_Reg mylib [] = {
   {"print", print},

There already is a global print function in Lua's base library (which you load in your luaL_openlibs() call).

   {"test", test},
   {NULL, NULL} /* end of array */
};

static int test(lua_State* L)
{
lua_pushinteger(L,5);
lua_pushfstring(L,"test");
lua_pushboolean(L,1);
return 3;
}

static int print(lua_State* L)
{
int nargs = lua_gettop(L);
  for (int i=1; i <= nargs; ++i) {
  printf( lua_tostring(L, i));

And here is your problem: lua_tostring returns NULL for Lua values that are not strings or numbers. You probably wanted luaL_tolstring. Also it is dangerous to let someone else (like the script writer) supply printf with the format string. Use

    printf( "%s", luaL_tolstring( L, i, NULL ) );

instead.

     }
     printf("\r\n");

'\r' should be unnecessary on Windows since stdout usually is opened in text-mode, and will produce unwanted control characters on other OSes.

return 0;
}


int main()
{
     lua_State *l = luaL_newstate();
luaL_openlibs(l);
  lua_getglobal(l, "_G");
luaL_setfuncs(l, mylib, 0);
lua_pop(l, 1);

if(luaL_loadfile(l,"D:\\Michael\\Desktop\\lua\\Debug\\test.lua")==0)
{
lua_pcall(l,0,0,0);
}
else
{
  printf("Failed to run script: %s\n", lua_tostring(l, -1));

Same problem as above: lua_tostring could return NULL. error()-calls with non-string arguments are rare but possible.

}
     lua_close(l);

     return 0;
}


HTH,
Philipp