Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let Lua overwrite global variables

Tags:

lua

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.

like image 412
ekd123 Avatar asked Apr 19 '26 08:04

ekd123


2 Answers

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
> 
like image 147
Doug Currie Avatar answered Apr 21 '26 23:04

Doug Currie


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?

like image 45
Nicol Bolas Avatar answered Apr 21 '26 23:04

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!