🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

with for lua

Started by
5 comments, last by amedlock 20 years ago
Lua is so powerful....I was filling in a table/object in lua and I wanted a with statement like Delphi has, so 20 lines of lua later I had one!! Outside of Lisp/Scheme Lua is the only language that never seems to leave me wanting.....and lua is a LOT more readable to come back to.


-- Delphi like with statement
function with(obj)
  local store = { {}, obj, _G[''__with''] }
  local vars = store[1]
  for k,v in obj do
    vars[k] = _G[k]
    _G[k] = obj[k]                     
  end
  _G[''__with''] = store
end

function endwith()
  local storage = _G[''__with'']
  if not storage then return end
  local vars = storage[1]
  local obj = storage[2]
  for k,v in vars do
    obj[k] = _G[k]
    _G[k] = vars[k]
  end
  _G[''__with''] = storage[3]
end

--------------------------------------------------
-- test code below
--------------------------------------------------

a = { x=100,
      printme = function(...) for k,v in ipairs(arg) do print(''arg''..k,v) end end
    }
for k,v in a do print( "a."..k, v) end

x = 50

with(a)
  x= 100
  printme("Hello",x)
  x= 150
  printme("Hello",x)
endwith()

print("x=",x)
for k,v in a do print( "a."..k, v) end

-- following should fail, printme was defined in a
ok, msg = pcall(printme, "Hello")
if ok then print(''Function printme OK.'' ) else
  print("Function printme failed:"..msg ) end
Advertisement
It gets even easier than that, through the use of function environments. See the manual for details, in particular the getfenv and setfenv functions.

"Sneftel is correct, if rather vulgar." --Flarelocke
We should turn this into a "Lua scraps" thread. Here are the homebrewed functions I use to serialize my level data for my sidescroller.

I just open a file and write out the string returned from serialize, which I just pass the entire level table to. Then that file can be loaded anytime and returns the exact same table. Note: it doesn''t work with threads or functions, and for userdata, the user has to define a toString method.

indent = 3function serialize(t)	indentation = 0	local str = "local t = " .. textize(t,3) .. " ; return t; "	return str	endfunction textize(t,indentation)		local str = "{ \n"			local tempk,tempv	local allnumbers=true 	for tempk,tempv in t do 		if type(tempk) ~= ''number'' then allnumbers=false end 	end  	 	str = str .. string.rep('' '',indentation)		for k,v in t do				if allnumbers == false then str = str .. string.rep('' '',indentation) end			if type(k) == ''number'' then			if allnumbers == false then				str = str .. ''['' .. k .. ''] = ''			end		elseif type(k) == ''string'' then			str = str .. ''["'' .. k .. ''"] = ''		else			error(''unknown key type in serialize'')		end				local a = type(v)				if a == ''number'' then			str = str .. v		elseif a == ''string'' then			str = str .. ''"'' .. v .. ''"''		elseif a == ''boolean'' then			if v then str = str .. ''true''			else str = str .. ''false'' end		elseif a == ''thread'' then			error(''cannot use threads in serialize'')		elseif a == ''userdata'' then			if v.toString == nil then				error(''to serialize a userdata you must define toString'')			end			str = str .. v:toString()		elseif a == ''table'' then			str = str .. textize(v,indentation + indent)					end				str = str .. '',''				if allnumbers == false then  str = str .. ''\n'' end			end		str = str .. ''\n'' .. string.rep('' '',indentation - indent) .. ''}''		return strend
quote: Original post by ktw6675
I just open a file and write out the string returned from serialize, which I just pass the entire level table to. Then that file can be loaded anytime and returns the exact same table. Note: it doesn't work with threads or functions, and for userdata, the user has to define a toString method.

Not to toot my own horn, but you may want to check out Pluto; support for saving arbitrarily complex and referential Lua structures, including functions, threads, and userdata. </avertisement>

(Edit: fixed misformatted link)

"Sneftel is correct, if rather vulgar." --Flarelocke

[edited by - sneftel on June 9, 2004 3:23:43 AM]
Um, Sneftel, ads work a lot better with information on how to get to the product. (His announcement thread was here.)
Wow...I''m impressed. Pluto looks pretty cool if I may say so myself. In addition to making saving/loading absolutely trivial (the entire "state" of the engine is entirely in Lua...I''m just itching to dump _G to file and load it back up and see things magically come back), this might allow me to do some interesting things with AI persistence and learning. Thanks for the link.
quote: Original post by ktw6675
I''m just itching to dump _G to file and load it back up and see things magically come back
It''s tricky right now, since you''d need to fill the "permanents table" with every C function exported to Lua (including standard library functions). I''m working on that aspect right now; give it a few days.


"Sneftel is correct, if rather vulgar." --Flarelocke

This topic is closed to new replies.

Advertisement