lua数据类型

2018-06-06  本文已影响0人  Mad_Elliot

Lua中有8个基本类型分别为:nil、boolean、number、string、userdata、function、thread、 table。
可以使用type函数测试给定变量或者值的类型,返回string类型

function func1()
end
print(type(true))
print(type(12))
print(type(func1))
print(type(nil))

> boolean
> number
> function
> nil
1. nil(空)
  1. nil 类型表示一种没有任何有效值,它只有一个值 nil;
  2. 给全局变量或者 table 表里的变量赋一个 nil 值,等同于把它们删掉;
  3. 一个变量只要赋了其他值,它就不可能是nil,无论是 false还是零。

2. boolean(布尔值)

注:nil类型为false,无论0还是1都为true。


3. number(双精度类型的实浮点数)

Lua 默认只有一种 number 类型 -- double(双精度)类型,无论整数或者小数都是number类型的。


4. string(字符串)
html = [[
<html>
<head></head>
<body>
    <a href="http://www.runoob.com/">菜鸟教程</a>
</body>
</html>]]
print(html)
> print("2" + 6)
8.0
> print("2" + "6")
8.0
> print("2 + 6")
2 + 6
> print("a" .. 'b')
ab
> print(157 .. 428)
157428

5. table(表)
-- 创建一个空的 table
local tbl1 = {}
 
-- 直接初始表
local tbl2 = {"apple", "pear", "orange", "grape"}
local tab1 = {"小明","小强",key1 = "banana",key2 = "apple"}
tab1[3] = "小东"
tab1["key3"] = "candy"

for key, val in pairs(tab1) do
    print(key.." "..val);
end

print(tab1[4])

打印结果:

1 小明
2 小强
3 小东
key1 banana
key3 candy
key2 apple
nil

6. function(函数)
function f1()
    print("Hello!");
end
f2 = f1
f2()

> Hello!
function testFun(tab,fun) --传入一个表和一个方法
    for k ,v in pairs(tab) do --遍历表
        print(fun(k,v));  --打印方法返回值
    end
end

tab={key1="val1",key2="val2"}; --新建一个表
testFun(tab,
function(k,v) --匿名函数(没有声明的函数)
    return k.."="..v;
end
);

7. thread(线程)

线程跟协程的区别:线程可以同时多个运行,而协程任意时刻只能运行一个,并且处于运行状态的协程只有被挂起(suspend)时才会暂停。

8. userdata(自定义类型)

userdata 是一种用户自定义数据,用于表示一种由应用程序或 C/C++ 语言库所创建的类型,可以将任意 C/C++ 的任意数据类型的数据(通常是 struct 和 指针)存储到 Lua 变量中调用。

上一篇 下一篇

猜你喜欢

热点阅读