I have 2 lua scripts. One require another one. So how can I call it from a C program?
For example:
main.lua
local foo = require "foo"
function main()
foo.bar()
end
main()
foo.lua
function bar( )
io.write("hello, world!\n")
end
And this is my C program:
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int status, result;
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
status = luaL_loadfile(L, "main.lua");
if (status) {
fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
exit(1);
}
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) {
fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
exit(1);
}
lua_close(L);
return 0;
}
It throws a runtime error:
Failed to run script: main.lua:130: module 'foo' not found: no field package.preload['foo'] no file '/usr/local/share/lua/5.3/foo.lua' no file '/usr/local/share/lua/5.3/foo/init.lua' no file '/usr/local/lib/lua/5.3/foo.lua' no file '/usr/local/lib/lua/5.3/foo/init.lua' no file './foo.lua' no file './foo/init.lua' no file '/usr/local/lib/lua/5.3/foo.so' no file '/usr/local/lib/lua/5.3/loadall.so' no file './foo.so'
I think it is because foo.lua is not loaded into the lua virtual machine, but I can't find API like load files or do files. So what should I do?