lua-users home
lua-l archive

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


Mike Spencer wrote:
what is the best way to parse floating point values from an external file?

Make your external file a Lua script and load it with loadfile.

$ cat configfile.lua

local function formula(x, y) return 2*x+y end

Particles = 3
Emitter.delay = 0.001
Emitter.delayFuzz = formula(0,0)

section't1'
Particles = 10.1
Emitter.delay = 1.12e-3
Emitter.delayFuzz = formula(1,1)

section't2'
Particles = 10.2
Emitter.delay = 1.13e-3
Emitter.delayFuzz = formula(1,2)

section(1)
Particles = 1001
Emitter.delay = 1.23e-3
Emitter.delayFuzz = formula(2,1)

section(2)
Particles = 1002
Emitter.delay = 1.24e-3
Emitter.delayFuzz = formula(2,2)


$ lua -ldump -lautotable -i

t = readconfig'configfile.lua'
dump('t', t)
t = { -- t->table: 0x10045f98
 Emitter = { -- table: 0x100542f8->table: 0x10045f98
   delay        = 0.001;
   delayFuzz    = 0;
 };
 Particles    = 3;
 t1 = { -- table: 0x100543c8->table: 0x10045f98
   Emitter = { -- table: 0x10053e88->table: 0x10045f98
     delay        = 0.00112;
     delayFuzz    = 3;
   };
   Particles    = 10.1;
 };
 t2 = { -- table: 0x100542a0->table: 0x10045f98
   Emitter = { -- table: 0x10054378->table: 0x10045f98
     delay        = 0.00113;
     delayFuzz    = 4;
   };
   Particles    = 10.2;
 };
 [1] = { -- table: 0x10054238->table: 0x10045f98
   Emitter = { -- table: 0x10054260->table: 0x10045f98
     delay        = 0.00123;
     delayFuzz    = 5;
   };
   Particles    = 1001;
 };
 [2] = { -- table: 0x10040880->table: 0x10045f98
   Emitter = { -- table: 0x100408a8->table: 0x10045f98
     delay        = 0.00124;
     delayFuzz    = 6;
   };
   Particles    = 1002;
 };
};


$ cat autotable.lua

local function auto_index(tab, key)
 local value = autotable()
 rawset(tab, key, value)
 return value
end

local auto_mt = {__index = auto_index}

function autotable(tab)
 return setmetatable(tab or {}, auto_mt)
end

function readconfig(filename, config)
 local f = assert(loadfile(filename))
 config = config or autotable()
 local g = getfenv(2)  -- globals
 local mt = { __newindex=config, config=config }
 function mt.__index(tab, key)
   local value = g[key]  -- first check globals
   if value ~= nil then return value end
   return mt.__newindex[key]  -- return config[key]
 end
 setfenv(f, setmetatable({}, mt))  -- use proxy
 return config, f()
end

function section(name)
 local mt = getmetatable(getfenv(2))
 local config = assert(mt.config, 'only call section in config files')
 local sec = autotable()
 config[name] = sec
 mt.__newindex = sec
end

Also see: http://lua-users.org/wiki/AutomagicTables

Cheers,

- Peter Shook

_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus