[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Simple data definition by swapping global table.
- From: Björn De Meyer <bjorn.demeyer@...>
- Date: Fri, 17 Jan 2003 00:17:50 +0100
Attached to this mail is a small example of how data
definitions can be made to look very easy by
swapping the global table. It allows
you to write
ITEM
"sword3"
name = "Silver
Sword"
price =
1000
attack =
15
DONE ""
And, then the data for name, price, and attack will be
stored in a table in ITEMS.sword3. Is this the best
way to do this, or should I consider changing the
metatable of the global environment in stead?
Comments anyone?
--
"No one knows true heroes, for they speak not of their greatness." --
Daniel Remar.
Björn De Meyer
bjorn.demeyer@pandora.be
--
-- easydata.lua
-- Module that alows for easier data
-- definition. For Lua 5.0
--
-- Copyright Bjorn De Meyer, 2002
--
easydata = {}
easydata.descriptors = {}
easydata.oldglobals = false;
easydata.functions = {};
-- the functions that need be available within a data block.
function DATADONE(fake, depth)
if not easydata.busy then return end;
-- do nothing if not busy.
easydata.busy = false
depth = depth or 2
for k,v in pairs(easydata.functions) do
easydata[easydata.lasttype][easydata.lastname][k] = nil;
end
-- We don't need these anymore.
setglobals(depth, easydata.oldglobals)
easydata.oldglobals[easydata.lasttype] =
easydata[easydata.lasttype]
-- Copy the data type to the old global table
-- We have to preserve easydata[easydata.lasttype]
-- because more items may need to be added yet.
end
function DATA(datatype, dataname, depth)
depth = depth or 2;
if easydata.busy then
-- automatically call DATADONE
DATADONE("fake", depth);
end
easydata.oldglobals = getglobals(2);
-- Get the old global table.
easydata.lasttype = datatype
easydata.lastname = dataname
-- store these, we need them.
easydata.busy = true;
-- now we are busy again.
if not easydata[datatype] then
easydata[datatype] = {}
-- empty table to hold the data
end
easydata[datatype][dataname] = {};
-- and create an empty table to hold what will be stored.
for k,v in pairs(easydata.functions) do
easydata[datatype][dataname][k] = v;
end
-- be sure we can still get out, though!
setglobals(depth, easydata[datatype][dataname])
end
function ITEM(name)
DATA("ITEMS",name,3);
end
easydata.functions.DATADONE = DATADONE;
easydata.functions.DONE = DATADONE;
easydata.functions.ITEM = ITEM;
easydata.functions.DATA = DATA;
-- fill this in at your leasure
ITEM "sword1"
name = "Short Sword"
price = 100
attack = 5
DONE "sword1"
ITEM "sword2"
name = "Long Sword"
attack = 10
price = 500
ITEM "sword3"
name = "Silver Sword"
price = 1000
attack = 15
DONE ""
-- the parameter to DONE is fake, only used for calling DONE
for k,v in pairs(ITEMS) do
print(k,v)
for i,n in pairs(v) do
print("=>", i, n)
end
end