Game Development Reference
In-Depth Information
_G["myVar"] = _G["myVar"] + 1
print(myVar)
_G.myVar = _G.myVar + 1
print(myVar)
How the Code Works
We start our code with declaring a global variable called myVar and assigning it a value of 1, and
then we print it to the screen. Next we increment it by 1 using myVar = myVar + 1 . This time we print
the value again, but instead of using print(myVar) , we access it directly from the global table _G via
print(_G["myVar"]) . Then we increment the variable by 1 again but using _G["myVar"] and print the
value using print(myVar) .
Lastly, we increment the value again by 1, but this time we access it using the _G.myVar method
to access the value and print the results. The idea of this exercise is to demonstrate how Lua uses
global variables and how they can be accessed using _G .
Note Though global variables can be accessed in this manner, it is suggested that local variables be
used instead; this reduces the number of variables used, saves on stack memory, and also had a speed
advantage over global variables.
Back to our saving and loading of data, we want to consolidate our data into one file so that we
can read our data in one go. In our modified version, we are reading the data into an array called
results . The only issue is that to access the values, we need to access the data by the numbered
index—but how would we know what each numeric index corresponds to?
Let's try to read the data and also set the global variables with the values.
function readFromFile(filename)
local results = {}
local hfile = io.open("filename")
if hfile==nil then return end
local lineNo = 0
for line in hFile:lines() do
table.insert(results, line)
lineNo = lineNo + 1
if lineNo == 1 then
_G["score"] = line
elseif lineNo == 2 then
_G["lives"] = line
elseif lineNo == 3 then
_G["health"] = line
elseif lineNo == 4 then
_G["level"] = line
end
end
return results
end
 
 
Search WWH ::




Custom Search