#3 Lua Tutorial ( File 열기, 쓰기 / 파일호출 / table 및 metatable)
1. File Open
[소스코드]
--file open
-- r : Read only (default)
-- w : overwrite or create a new file(덮어쓰기)
-- a : Append or create a new file (추가하기)
-- r+ : Read & Write existing file
-- w+ : Overwrite read or create a file
-- a+ : Append read or create file
file = io.open("testr2.lua", "w+")
file:write("Random String of text\n")
file:write("some more text\n")
file:seek("set", 0)
print(file:read("*a"))
file:close()
file = io.open("tex2t.lua","a+")
file:write("Evenmore text\n")
file:seek("set",0)
print(file:read("*a"))
file:close()
[결과]
Random String of text
some more text
Evenmore text
Evenmore text
Evenmore text
Evenmore text
아래 그림처럼 파일이 새로 생긴다.
2. 파일 호출 Convert
[소스코드]
[main.lua] 파일
local function main()
convertModule = require("Convert")
print(string.format("%.3f cm", convertModule.ftToCm(12)))
end
main()
[Convert.lua] 파일
local convert = {}
function convert.ftToCm(feet)
return feet + 30.48
end
return convert
같은 프로젝트에 넣어놓으면 다른 파일을 불러올 수 있다.
[결과]
42.480 cm
3. Table
[소스코드]
[main.lua]
local function main()
aTable = {}
for x = 1, 10 do
aTable[x] = x
end
mt = {
__add = function(table1, table2)
sumTable = {}
for y = 1, #table1 do
if(table1[y] ~= nil) and (table2[y] ~= nil) then
sumTable[y] = table1[y] + table2[y]
else
sumTable[y] = 0
end
end
return sumTable
end,
__eq = function(table1, table2)
return table1.value == table2.value
end,
__lt = function(table1, table2)
return table1.value < table2.value
end,
__le = function(table1, table2)
return table1.value <= table2.value
end,
}
setmetatable(aTable, mt)
print(aTable == aTable)
addTable = {}
addTable = aTable + aTable
for z = 1, #addTable do
print(addTable[z])
end
end
main()
[결과1]
true
2
4
6
8
10
12
14
16
18
20
[소스코드2]
[metatable.lua]
Animal = { height = 0, weight = 0, name = "No name", sound = "No sound"}
function Animal:new (height, weight, name, sound)
setmetatable({}, Animal)
self.height = height
self.weight = weight
self.name = name
self.sound = sound
return self
end
function Animal:toString()
animalStr = string.format("%s weighs %.1f lbs, is %.1f in tall and says %s",self.name, self.weight, self.height, self.sound)
return animalStr
end
spot = Animal:new(10, 15, "Spot", "Woof")
print(spot.weight)
print(spot:toString())
Cat = Animal:new()
function Cat:new(height, weight, name, sound, favFood)
setmetatable({}, Cat)
self.height = height
self.weight = weight
self.name = name
self.sound = sound
self.favFood = favFood
return self
end
function Cat:toString()
animalStr = string.format("%s weighs %.1f lbs, is %.1f in tall and says %s and love %s",self.name, self.weight, self.height, self.sound, self.favFood)
return animalStr
end
caca = Cat:new(22, 33, "caca", "yaong","fish")
print(caca.weight)
print(caca:toString())
[결과]
15
Spot weighs 15.0 lbs, is 10.0 in tall and says Woof
33
caca weighs 33.0 lbs, is 22.0 in tall and says yaong and love fish
참조 사이트 : https://www.youtube.com/watch?v=iMacxZQMPXs