練習1.1
輸入負數時,會產生無限遞歸,引發堆棧溢出。只需加個負數判斷即可
function fact(n)
if n<0 then
return "error input"
elseif n==0 then
return 1
else
return n*fact(n-1)
end
end
練習1.2
將twice函數寫在 mylualib.lua 文件下
function twice(x)
return 2.0*x
end
print(twice(2))
lua -lmylualib " " 或 在交互模式下dofile("mylualib.lua")
我更喜歡dofile,可以在編輯器編輯完畢後,直接使用dofile查看代碼運行結果,雖然lua -l也能達到同樣效果,但是dofile更有望文生義的感覺。
練習1.3
目前不知道
練習1.4
___ _end End NULL
練習1.5
false,因爲 type 函數的返回值類型是string
練習1.6
檢查是否爲 true 和 false 即可
if x == "true" then
print("type x is bool")
elseif x == "false" then
print("type x is false")
end
練習1.7
不是必須的;加上括號會讓程序可讀性提高。
練習1.8
解釋器執行的腳本文件名存儲在 arg[0] 中。
print(arg[0])