Code archives/Miscellaneous/Lua For-Each Function
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
| I did a lot of hunting down, at first I thought it was too crazy to work, but it does work. I wanted a easy way to go through a TList object inside of Lua. So I came up with the idea of just passing the TList object, and passing a anonymous function to do for each member. The function will only receive one argument right now, and that's the object. I initially tried having LuGI take care of the BMX function, but it turned out way easier to just register it manually. What I did with the temporary function was put it in a temporary register which each object of the loop can run, then at the end it releases the register. Please share any improvements you make! Here's an example of how to use it in Lua: ForEach(CurrentSystem.PlanetList, function (planet) DrawText(planet.Name.." : "..planet.oAngle, SCREENW/2-128, 0+(16*Planet_Count)) Planet_Count=Planet_Count+1 end ) -- Or even clearer: ForEach(ListObject, function (ListMember) --Do operations here end ) | |||||
''' Put somewhere after you start your LuaState
lua_register( lua_state, "ForEach", ForEach )
''' The actual function
Function ForEach:Int( lua_vm:Byte Ptr )
Local _arg_1:TList = Null
If lua_gettop(lua_vm) > 1
_arg_1 = TList(lua_tobmaxobject(lua_vm, 1))
If lua_isfunction(lua_vm,2)
Local tmpFunc% = luaL_ref(lua_vm, LUA_REGISTRYINDEX)
For Local tmp:Object = EachIn _arg_1
'call luaFunc
lua_rawgeti(lua_vm,LUA_REGISTRYINDEX,tmpFunc)
lua_pushbmaxobject(lua_vm,tmp)
If lua_pcall( lua_vm, 1, 1, 0 ) Then
scriptError = lua_tostring( lua_vm, -1 )
lua_pop( lua_vm, 1 )
Notify("ForEach :: "+scriptError)
scriptIsGood = False
'Else
' Get the result
'local result% = lua_tointeger( luaState, -1 )
EndIf
lua_pop( lua_vm, 1 )
Next
luaL_unref(lua_vm,LUA_REGISTRYINDEX,tmpFunc)
EndIf
End If
lua_pushinteger( lua_vm, 0 )
Return 1
End Function |
Comments
| ||
| By request: http://www.blitzbasic.com/codearcs/codearcs.php?code=2544 |
| ||
| Haha, second time I submit something and someone else did it better and proper. xD Well, I guess mine is at least a working case study on how to send a lua function to a BlitzMax function and execute it multiple times... |
Code Archives Forum