[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to load lua extensions using C API?
- From: Sean Conner <sean@...>
- Date: Thu, 8 Aug 2013 11:58:45 -0400
It was thus said that the Great Newton Kim once stated:
> I'm using lua 5.1.
> I'm making runtime engine that runs lua script.
> I want the lua is ready with my extensions when it is instantiated.
> (just as math or file is ready when the script is loaded)
> But, I don't want to touch the source code.
> I read the reference manual but failed.
> What C API should I call to let the lua engine load my extension?
> Thank you in advance.
To get to the state that Lua is in when you run the stand-alone interpreter,
you do:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
lua_State *L;
L = luaL_newstate();
if (L == NULL)
{
/* handle error */
}
lua_gc(L,LUA_GCSTOP,0);
luaL_openlibs(L);
lua_gc(L,LUA_GCRESTART,0);
To load your extentions, you have a few options. To make it so you don't
require "require" to load your extension:
lua_pushliteral(L,"nameofyourmodule");
luaopen_nameofyourmodule(L);
If you are using Lua 5.2, you'll need to set the return value (if it isn't
an error) to some global variable; otherwise, for Lua 5.1, that's already
been done for you. The module is now immediately ready without having to
use "require" to load it.
If you want to use require, you could always do (after calling
luaL_openlibs()):
lua_getglobal(L,"package");
lua_getfield(L,-1,"preload");
lua_pushcfunction(L,luaopen_nameofyourmodule);
lua_setfield(L,-2,"nameofyourmodule");
The scripts will now need to "require" your module to work properly.
I cover some additional methods here:
http://boston.conman.org/2013/03/22.1
http://boston.conman.org/2013/03/23.1
-spc (Hope this helps)