[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Convert userdata to hex string
- From: steve donovan <steve.j.donovan@...>
- Date: Sun, 21 Feb 2010 11:53:50 +0200
On Sun, Feb 21, 2010 at 11:00 AM, Peter Smith <psmith135@gmail.com> wrote:
> Could someone please give a function sample that could do the trick? If it
> requires an extension it would great if it was working in win32.
Here she is, nice & simple (as C extensions go):
// a little extension to access arbitrary userdata as a string
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_as_string (lua_State *L) {
void *data = lua_touserdata(L,1);
int sz;
if (data == NULL) {
lua_pushnil(L);
lua_pushstring(L,"not userdata!");
return 2;
} else {
sz = lua_objlen(L,1);
lua_pushlstring(L,data,sz);
return 1;
}
}
static const luaL_reg userdata[] = {
{"as_string",l_as_string},
{NULL,NULL}
};
__declspec(dllexport)
LUALIB_API int luaopen_userdata(lua_State *L)
{
luaL_register (L, "userdata", userdata);
return 1;
}
(the _declspec(dllexport) is Windows stuff that can be removed)
Build against LfW libraries
cl /LD /I\lua\include userdata.c \lua\lib\lua5.1.lib
And here it is:
C:\lang\lua\projects> lua -luserdata
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s,err = userdata.as_string(io.stdout)
> = s
ÿ←∟x
> = #s
4
Which is exactly what we expect; the contents of a file userdata is a
pointer to the actual FILE* object. However, we are on shaky ground,
because the assumption is that module developers may change the
userdata representation as long as they keep the external API the
same.
Drop me a line if you have difficulty building this...
steve d.