为什么Lua中的==表现得像这样?

Gou*_*Das -7 printing lua

在我们输入的Lua解释器中:

>print(1=="1") 
 false 
Run Code Online (Sandbox Code Playgroud)

好的!

>print(false==true) 
 false
Run Code Online (Sandbox Code Playgroud)

好的!

>print(string==math) 
 false
Run Code Online (Sandbox Code Playgroud)

好的但为什么呢?

>print(function==nil) 
 stdin:1: '(' expected near '=='
Run Code Online (Sandbox Code Playgroud)

我不明白==和〜=的工作原理.请解释

Pig*_*let 6

print(function==nil) 
Run Code Online (Sandbox Code Playgroud)

给你错误信息:

stdin:1:'('预计在'=='附近

因为function是用于定义函数变量的关键字.该关键字应该在某种语法中使用.function它本身不是一个有效的Lua表达式,因此不能用作一个表达式.Lua告诉你,你写了一些它无法解释的东西,并且通常会期望它function被跟随(.

请阅读https://www.lua.org/manual/5.3/manual.html#3.4.11https://www.lua.org/manual/5.3/manual.html#3.4https:// www. lua.org/manual/5.3/manual.html#3.4.5

还有别的:)

字符串和数学都是Lua标准库.字符串和数学是两个不同的Lua表.因此它们不能相同,因此表达式string == math是false.

来自https://www.lua.org/manual/5.3/manual.html#3.4:

Lua中的基本表达式如下:

exp :: = prefixexp

exp :: = nil | 假| 真正

exp :: =数字

exp :: = LiteralString

exp :: = functiondef

exp :: = tableconstructor

exp :: ='...'

exp :: = exp binop exp

exp :: = unop exp

prefixexp :: = var | functioncall | '('exp')'

如您所见,只有Lua关键字为nil,false和true都是表达式.其他关键字不是.

math和string根本就没有Lua关键字.它们是类型表的变量.变量也是表达式.这就是你没有得到错误的原因math == string

通过阅读Lua的参考手册和Lua编程,可以最好地回答这样的问题.

https://www.lua.org/docs.html

我不是说你应该知道你开始的所有事情.但了解基础知识将加速您的学习体验和您的理解!