Collaborative Multithreading in Lua

BlitzMax Forums/BlitzMax Programming/Collaborative Multithreading in Lua

Starkkz(Posted 2013) [#1]
Hello, after lots of attempts in trying to create a multithreading module in Lua I stepped with lua_newthread and finally made a tiny and primitive collaborative multithreading program. I'll leave it here for your purposes.

Type TLuaThread
	Field ParentState:Byte Ptr
	Field State:Byte Ptr
	Field Code:String
	
	Function RunThread:Object(LT:Object)
		Local LuaObject:TLuaThread = TLuaThread(LT)
		If LuaObject Then
			LuaObject.State = lua_newthread(LuaObject.ParentState)
			luaL_dostring LuaObject.State, LuaObject.Code
			
			Local Error:String = lua_tostring(LuaObject.State, -1)
			If Len(Error) > 0 Then Print "Error: "+Error
		EndIf
	EndFunction
	
	Method Run:TThread()
		Local Thread:TThread = CreateThread(TLuaThread.RunThread, Self)
	EndMethod
	
	Method Create:TLuaThread(ParentState:Byte Ptr,Code:String)
		Self.ParentState = ParentState
		Self.Code = Code
		Self.Run()
		Return Self
	EndMethod
EndType

Function lua_CreateThread(L:Byte Ptr)
	Local Code:String = luaL_checkstring(L, 1)
	If Len(Code) > 0 Then
		New TLuaThread.Create(L, Code)
	EndIf
EndFunction


As I said it's very primitive because it just contains the BlitzMax function, you have to register it yourself with lua_register to be able to use it in Lua. GL!