lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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

name = "Silver
price =
attack =
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
-- 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;

-- We don't need these anymore.
setglobals(depth, easydata.oldglobals)
easydata.oldglobals[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.

function DATA(datatype, dataname, depth)

depth = depth or 2;

if easydata.busy then
-- automatically call DATADONE
    DATADONE("fake", depth);

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

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;
-- be sure we can still get out, though!
setglobals(depth, easydata[datatype][dataname])

function ITEM(name)

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
for i,n in pairs(v) do
print("=>", i, n)