[LUA] Chap 8. Compile, Execution, Error

[예제]
f = load("i = i + 1")
i = 0
f(); print(i)
f(); print(i)
--assert(load(s))()
i = 32
local i = 0
ff = load("i = i + 1; print(i)") -- refer to global variable, 실행할 때마다 컴파일
g = function () i = i + 1; print(i) end --refer to local varaiable, 한 번만 컴파일 하면 됨
ff()
g()
print "enter your expression: "
local l = io.read()
local func = assert(load("return " .. l)) -- return 뒤에 띄어쓰기를 하지 않으면 에러가 난다. 숫자만 입력가능한듯 하다.
print("the value of your expression is " .. func())
--"변수 X를 써서 별(*)을 출력할 개수를 반환하는 함수의 정의를 입력하시오."
print "enter function to be plotted (with variable 'x'):" --숫자를 넣는다.
local l = io.read()
local f = assert(load("return " .. l)) -- return 뒤에 띄어쓰기를 하지 않으면 에러가 난다.
for ii1 = 1, 20 do
  x = i
  print(string.rep("*", f())) --별의 갯수를 반환한다. 10을 넣었다면 *을 10개씩 20번을 표시한다.
end

--io.lines is valid after LUA 5.2
--[[fkf = load(io.lines(filename, "*L"))
fkf2 = load(io.lines(filename, 1024)) --1024byte
--]]
print "enter function to be plotted 2(with variable 'x'):"
local l = io.read()
local f = assert(load("local x = ...; return " .. l)) -- return 뒤에 띄어쓰기를 하지 않으면 에러가 난다.
for ii3 = 1, 20 do
  x = ii3
  print(string.rep("*", f()))
end

p = loadfile(arg[1])
f = io.open(arg[2], "wb")
f:write(string.dump(p))
f:close()



[결과]
1
2
33
1
enter your expression:
3
the value of your expression is 3
enter function to be plotted (with variable 'x'):
3
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
enter function to be plotted 2(with variable 'x'):
3
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***

[예제]
--if input is not a number, return error.
print "enter a number:"
n = io.read("*n")
if not n then error("invalid input") end
print "enter a number:"
k = assert(io.read("*n"), "invalid input")

local file, msg
repeat
  print "enter a file name:"
  local name = io.read() 
  if not name then return end
  file, msg = io.open(name, "r")
  if not file then print(msg) end
 
 until file
 file = assert(io.open("no-file", "r"))


[결과]
enter a number:
3
enter a number:
4
enter a file name:
: Invalid argument
enter a file name:
5
5: No such file or directory
enter a file name:
[LUA] Chap 8. Compile, Execution, Error [LUA] Chap 8. Compile, Execution, Error Reviewed by kukanuc on 3월 10, 2019 Rating: 5

댓글 없음:

Powered by Blogger.