|
It was thus said that the Great Igor Trevisan once stated:
> Hi Thijs,Somehow, your C application will need to know where file_x.lua resides.
>
> thanks for answering!
>
> On 30 April 2014 09:48, Thijs Schreijer <thijs@thijsschreijer.nl> wrote:
>
> >From your description it seems that you "run files" and not specifically
> > Lua code or functions. Especially your wording "meld them in a single
> > bytecode".
> >
> I want to execute a function witten in Lua calling it from my
> main application written in C.
>
> [...]
>
>
> > And though I don't understand exactly what and how you're trying to do
>
>
> I recall the example I used answering to a previous email in the thread.
> I hope it can help.
>
> Suppose I have defined func_y in file_y.lua
> and I want to use it within func_x that's in file_x.lua.
> func_x is the main lua function that has to be called and
> executed from my C code.
> file_x.lua and file_y.lua are both in a USB stick used
> in my embedded system to make lua functionalities avaliable
> when needed.
> Now the question is: how can I load and execute successfully
> func_x?
For sake of argument, let's just pass it in on the command line. So we
have (I'm assuming Lua 5.2):
#include <stdlib.h>
#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main(int argc,char *argv[])
{
lua_State *L;
int rc;
/* check to see if Lua file specified */
if (argc == 1)
{
fprintf(stderr,"usage: %s luafile\n",argv[0]);
return EXIT_FAILURE;
}
/* create Lua state */
L = luaL_newstate();
if (L == NULL)
{
fprintf(stderr,"could not initialize Lua\n");
return EXIT_FAILURE;
}
/* initialize standard Lua modules like io and math */
luaL_openlibs(L);
/* load our file */
rc = luaL_loadfile(L,argv[1]);
if (rc != LUA_OK)
{
const char *errmsg = lua_tostring(L,-1);
fprintf(stderr,"%s: %s\n",argv[1],errmsg);
lua_close(L);
return EXIT_FAILURE;
}
/* load the file */
rc = lua_pcall(L,0,0,0);
if (rc != LUA_OK)
{
const char *errmsg = lua_tostring(L,-1);
fprintf(stderr,"executing %s: %s\n",argv[1],errmsg);
lua_close(L);
return EXIT_FAILURE;
}
/* now call our function */
lua_getglobal(L,"func_x");
rc = lua_pcall(L,0,0,0);
if (rc != LUA_OK)
{
const char *errmsg = lua_tostring(L,-1);
fprintf(stderr,"func_x() = %s",errmsg);
lua_close(L);
return EXIT_FAILURE;
}
lua_close(L);
return EXIT_SUCCESS;
}
That's fine if file_x.lua doesn't require other Lua files. If it does, then
things get ... system specific. file_x.lua needs to know where file_y.lua
resides, and there are multiple ways of having file_x.lua load the file. It
can do:
dofile "file_y.lua"
or
do
local x = loadfile "file_y.lua"
x()
end
or
require "file_y.lua"
The first two are pretty much equivalent and assume that no path is
required to specify the file. The last depends upon how the environment
variable LUA_PATH is set, and the internal value package.path.
-spc