lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

I've got a question regarding the use of the C API. I can manage what
I want to do, but my code seems clumsy, so I am wondering if I am
missing an easier idiom to do what I want.

I am interfacing Lua to an application which uses Unicode exclusively
for all of its internal processing (specifically, Win32 wide
characters). The application APIs all work in terms of wide
characters. So, at the boundary between Lua and the application, I
need to convert data between char and wchar_t types.

The biggest issue I have is that converting char <-> wchar_t requires
memory buffers for the conversion. I can obtain these in a number of
ways (the lua allocator, creating userdata objects, etc) but I need to
manage the lifetime of the buffers.

I've written helper functions
    int luaU_pushunicode(lua_State *L, wchar_t *str)
    wchar_t *luaU_checkunicode(lua_State *L, int index)

modelled on the lua equivalents for strings. However, I still find
places where I need char* arguments rather than strings on the stack
(one notable place is when I define a lua_Reader, another is

I'm finding it difficult to keep the layers separate, which means I'm
ending up with more memory management calls, and error handling
checks, than I'd like. I realise it's difficult to comment without
details, but has anyone got any advice for me (or better still,
pointers to sample code that might help!) on how to keep the interface
between lua and the host application tidy? The reference is a bit
short on samples, and I didn't see much in (the first edition of)
Programming in Lua. There's lots of sample code on the wiki, but I
didn't see anything that looked helpful.

Thanks for any help,

PS One thing that surprised me was that there's no equivalent of
luaL_loadbuffer which takes a Lua string on the stack. I guess I could
use luaL_loadstring along with lua_tostring, but I then need to check
for errors from lua_tostring before proceeding. Hmm, maybe it's just
that it's been so long since I did any serious C programming that I'd
forgotten how messy error handling in C could get :-(