Lua Table

Posted by Tkl1129 on Wed 10 Aug 2011 02:26 AM — 2 posts, 14,921 views.

Hong Kong #0
I'm try to use Lua table instead of SQLite, I've got a problem.

Case here:
I wanna search for some specific key inside.


require("tprint")

Map = {}
	Map.sz = {}
		Map.sz.sz01 = {	Code = "sz01",
						Area = "sz",
						Location = "Tower",
						CP = 1,
						Range = 3,
					}
		Map.sz.sz02 = {	Code = "sz02",
						Area = "sz",
						Location = "Hotel",
						CP = 0,
						Range = 4,
					}
	Map.yz = {}
		Map.yz.yz01 = {	Code = "yz01",
						Area = "yz",
						Location = "Center",
						CP = 1,
						Range = 3,
					}
					
tprint(Map)




By this table, If I only got 1 information, Location = "Center", how can I search back which Code of this area?
For example, "Search Location "Center" and then return the code "yz01"....that is what I want to get, but don't know how to do it in Lua, Thanks.
USA #1

function ScanLocation(locStr)
  for area,areaTable in pairs(Map)do
    for code, codeTable in pairs(areaTable) do
      if codeTable.Location == locStr then
        return code
      end 
    end
  end
end
 


Since codeTable.Code is the same as the keyname of codeTable it'll work quicker. If you want to hard code it for clarity or fringe cases where your t.Code will be different, then return codeTable.Code instead... Also, if you start putting values in there there other than tables. (i.e. sz.Name = "Foo", sz.Builder = "Nick" or something) you'd want to wrap the second for in a if type(areaTable) == "table" check.