ekd123
ekd123

Reputation: 535

Let Lua overwrite global variables

I'm using Lua as the configuring language. As everybody knows, configuration should have system-wide one and user's one.

I just found that Lua would keep the original values rather than overwrite them.

For example,this is the first source file,

-- a.lua
var=1

and the second source file

-- b.lua
var=2

here's the result:

> lua-5.1 
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> dofile ("a.lua")
> dofile ("b.lua")
> print(var)
1

Yep. var has not been overwritten. This would make user's own configuration not work. Anybody knows how to let Lua overview variables which have the same variable name by default? Thanks very much. (source above is just for example, actually I'm using Lua with C)

PS: I checked the test above again and it works. Please see comments under the answer of Nicol.

Upvotes: 3

Views: 1751

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 473252

I attempted to reproduce your error, but it worked exactly as you expected it would. So if you're getting this, it is almost certainly something you're doing somewhere that you're not mentioning. Are you sure those files contain what you say they do?

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41170

The usual approach is to have a table of system parameters, and a table of user parameters. E.g.,

a.lua

sys = { var = 1; a = 3 }

b.lua

usr = { a = 5; b = 7 }

The config manager does

setmetatable(usr,{__index = sys})

Test:

> =usr.a
5
> =usr.var
1
> =usr.b
7
> 

Upvotes: 3

Related Questions