Skip to content

Instantly share code, notes, and snippets.

@nilium
Created March 16, 2009 23:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilium/80159 to your computer and use it in GitHub Desktop.
Save nilium/80159 to your computer and use it in GitHub Desktop.
Example of Lua reflection code
' test.bmx
Type Foo {expose}
Method Bazzle( obj:Bar )
If obj = Null Then
Print "Null obj"
Else
Print obj.ToString()
EndIf
End Method
End Type
Type Bar {expose}
Method ToString:String()
Return "Woopertonville"
End Method
End Type
Type FooBar Extends Foo {expose}
End Type
Type Common {expose static noclass}
' Some wrapper functions are necessary, since I cannot really do anything about exposing regular functions
Method luaOpenFile:TStream( file:String, mode:String ) {rename="OpenStream"}
Local read:Int, write:Int
read = False
write = False
If mode.Contains("r") Then
read = True
EndIf
If mode.Contains("w") Then
write = True
EndIf
Return OpenFile( file, read, write )
End Method
End Type
' Exec
Local vm:Byte Ptr = luaL_newstate()
' Call this to implement any types with the proper attributes/metadata
lua_implementtypes(vm)
' Example of forcing exposure of a type (handy when you don't want to or can't modify source)
lua_implementtype( vm, TTypeId.ForName("TStream"), True, False, False )
If lua_dofile( vm, "test.lua" ) <> 0 Then
Print "[ERROR] "+lua_tostring( vm, -1 )
EndIf
lua_close(vm)
vm = Null
Input("Done.")
-- test.lua
-- Random stuff
local foo,bar
foo = NewFooBar()
bar = NewBar()
foo:Bazzle(bar)
foo:Bazzle(nil)
bar:Delete()
foo:Delete()
-- Once :Delete() is called, the object is no longer usable, as the table is
-- cleared out. If you have any data being stored inside the object's table,
-- make damn sure you've got it stored elsewhere. I don't know why you'd
-- attach anything to the object, it's a bad idea, but whatever.
-- TStream
local mystream = OpenStream("woop.txt","w")
mystream:WriteString("Wooperton, yo.")
mystream:Close()
-- You may still call mystream:Delete(), but it is not required
mystream = nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment