[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re:Registering C funcs with args
- From: Philippe Lhoste <PhiLho@...>
- Date: Mon, 15 Jul 2002 12:12:31 +0200 (MEST)
> Hi! I'm new to Lua, and I was wondering, how do you
> register C functions with arguments in Lua? I've read
> the reference manual, and I think there's no example
> of that there.
>
> BOOL DisplayString(lua_State * L, const char
> *pString);
>
> How would you register something like this? Or is
> wrong in the first place? The original function was
> without the lua_State (obviously).
A good example of implementation of a library in Lua is in the source code
of Lua, under src/lib. Here you can see how the standard library of Lua is
implemented.
To answer your question, all C functions you register in Lua have the same
signature:
int LuaFunction(lua_State *L)
For example:
static int io_getenv (lua_State *L) {
lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil
*/
return 1;
}
I rewrite it to:
static int io_getenv (lua_State *L) {
/* Get parameters, here a string */
char *envVar = luaL_check_string(L, 1);
/* Process the parameter(s): call the real C function */
char *envVal = getenv(envVar);
/* Set the return value(s) */
lua_pushstring(L, envVal); /* if NULL push nil */
/* Return the number of return values */
return 1;
}
for easier reading.
As you can see, you have to pop out the parameters of the Lua function from
the stack.
The C function is called with these parameters.
Then you push the results (a Lua function can have several return values) in
the stack and indicate the number of results to the Lua engine.
You have to wrap all the C functions of your library in specific similar
functions, either as a thin wrapper, like this, or in more complex operations
hidding the original process. Eg. you can make a Lua function outputting the
list of files of a directory, wrapping the calls of findfirst() and findnext().
Regards.
--
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
Philippe Lhoste (Paris -- France)
Professional programmer and amateur artist
http://jove.prohosting.com/~philho/
--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--=#=--
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net