Lua 1 Getting started

注释

单行注释:
--这里是注释  

多行注释:
--[[
    一些注释
--]]

全局变量

print(b) --> nil
b = 10
print(b) --> 10

运行环境

#!/usr/local/bin/lua
#!/usr/bin/env lua

命令行

$lua -e "print(math.sin(12))"
$lua -i -llib -e "x = 10"

命令行参数

% lua -e "sin=math.sin" script a b
The interpreter collects the arguments as follows:
arg[-3] = "lua"
arg[-2] = "-e"
arg[-1] = "sin=math.sin"
arg[0] = "script"
arg[1] = "a"
arg[2] = "b"

type:

print(type("Hello world"))  --> string
print(type(10.4 * 3))       --> number
print(type(print))      --> function
print(type(type))       --> function
print(type(true))       --> boolean
print(type(nil))        --> nil
print(type(type(X)))        --> string

function:

-- defines a factorial function

function fact(n)
    if n == 0 then
        return 1
    else
        return n * fact(n -1)
    end

end

print("input a number:")
a = io.read("*n")

print(fact(a))

dofile:

-->lib1.lua
function norm(x, y)
    return (x^2 + y^2)^0.5
end

function twice(x)
    return 2*x
end

-->2.lua  2.lua调用lib1.lua里的函数
dofile("lib1.lua")

n = norm(3.4, 1.2)
print(twice(n))

关键字

The following words are reserved; we cannot use them as identifiers:
and end if or until break false in repeat while do goto local
return else for nil then elseif function not true

猜你喜欢

转载自blog.csdn.net/u013420428/article/details/80412599