[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Arguments for a module loader
- From: Sean Conner <sean@...>
- Date: Tue, 7 Aug 2012 12:11:01 -0400
It was thus said that the Great Matthias Kluwe once stated:
> Hi!
>
> I must admit that I don't really understand the documentation of
> require (as given by
> http://www.lua.org/manual/5.2/manual.html#pdf-require).
>
> After reading it several times I gave up and decided to help myself by
> some example code. I wrote the following simple module:
>
> #include <stdio.h>
> #include <lua5.2/lua.h>
>
> int luaopen_mod( lua_State *L ) {
> printf( "stack size : %d\n", lua_gettop( L ) );
> printf( "typename 1: %s\n", lua_typename( L, 1 ) );
> printf( "typename 2: %s\n", lua_typename( L, 2 ) );
> printf( "value 1: %d\n", lua_toboolean( L, 1 ) );
> printf( "isuserdata 2: %d\n", lua_isuserdata( L, 2 ) );
> printf( "isstring 2: %d\n", lua_isstring( L, 2 ) );
> printf( "value 2: %s\n", lua_tolstring( L, 2, 0 ) );
> lua_newtable( L );
> return 1;
> }
>
> and compiled it with gcc -shared -o mod.so mod.c.
>
> When called by `require 'mod'` the output is
>
> stack size : 2
> typename 1: boolean
> typename 2: userdata
> value 1: 1
> isuserdata 2: 0
> isstring 2: 1
> value 2: ./mod.so
The major issue with your code is the use of lua_typename()---it doesn't
do what you think it does. lua_typename() returns the name of the given
type, such that 1 is LUA_TBOOLEAN, 2 is LUA_TUSERDATA. To get the type at
the given stack index, use luaL_typename(). If you try this:
#include <stdio.h>
#include <lua5.2/lua.h>
#include <lua5.2/lauxlib.h>
int luaopen_mod( lua_State *L ) {
printf( "stack size : %d\n", lua_gettop( L ) );
printf( "typename 1: %s\n", luaL_typename( L, 1 ) );
printf( "typename 2: %s\n", luaL_typename( L, 2 ) );
printf( "value 1: %s\n", lua_tostring( L, 1 ) );
printf( "isuserdata 2: %d\n", lua_isuserdata( L, 2 ) );
printf( "isstring 2: %d\n", lua_isstring( L, 2 ) );
printf( "value 2: %s\n", lua_tolstring( L, 2, NULL ) ); /* [1] */
/*-----------------------------------------------------------------------
; [1] - please, please, please, ifyou are writing in C, use NULL instead
; of a 0. Even though NULL is 0, using NULL portrays the intent
; better than a 0. It also stands out more.
;
; If you are writing in C++, you have my condolences. [2]
;
; [2] - Okay, my bias is showing through. Sorry.
;----------------------------------------------------------------------*/
lua_newtable( L );
return 1;
}
You should see:
stack size : 2
typename 1: string
typename 2: string
value 1: mod
isuserdata 2: 0
isstring 2: 1
value 2: ./mod.so
The first parameter is the string given to require() (compatible with Lua
5.1) while the second paramter is the filename that contains the module (new
for Lua 5.2).
-spc