Created
March 16, 2009 23:21
-
-
Save nilium/80159 to your computer and use it in GitHub Desktop.
Example of Lua reflection code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' 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.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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