tags:

views:

82

answers:

3

I am using swig-lua. I have a function in Lua which I call and it returns me a pointer (userdata). right now I know what this pointer is, but how can I tell Lua from within Lua?

+3  A: 

From the Lua Reference Manual:

setmetatable (table, metatable)

Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.)

You cannot "tell Lua" what a userdata is within Lua. It must be given a metatable or manipulated through bound function calls using the C API. See chapter 28.1 of Programming in Lua (Pil) for more information.

Judge Maygarden
A: 

The very definition of userdata is that Lua does not, can not, and doesn't want to know what it is. It's your data- what it is is your problem. If you want to manipulate it, then you must call C functions with it (operator overloads available by metatable setting).

DeadMG
I am not saying Lua should know. I know it can't, but can't SWIG say something?
John Smith
SWIG can only perform actions available in the default API, it can't rewrite the source or language. When lua_touserdata returns a void*, unless SWIG uses an internal, separate system to automatically handle this result and pass the correct type to you, all you can get is the void*.
DeadMG
A: 

Tell SWIG about the data type pointed at by that void pointer. If SWIG is aware of the type, then it will pass it to Lua as a userdata with a suitable metatable attached that allows the Lua side to access and modify the individual data fields, (and if it is a class, call call its methods).

This might mean telling SWIG about some data types that aren't otherwise required by the library, but is probably worth the effort in the long run.

All Lua knows about what type a userdata is is contained in its metatable. Two userdata values are the same type if they have the same metatable. That metatable is responsible for mediating all access to the its content from the Lua side, and is usually made up of methods implemented in C so that is possible to do. Without such a metatable, then the Lua side can only treat a userdata as an opaque blob.

RBerteig