What does an exclamation mark in Lua do?

梦想与她 提交于 2019-12-11 02:25:42

问题


Question is in the title, really. I saw someone use this earlier and I didn't know what the ! was used for.

local lowestIndex = 0;
local lowestValue = false;
for k, v in ipairs(playerElement) do
    if !lowestValue or v.value < lowestValue then
        lowestIndex = k;
        lowestValue = v;
    end
end

回答1:


As others have said, ! normally has no function in Lua, and the code you posted would not normally be valid. However, it's quite trivial to extend Lua's parser to allow for custom syntax, and it's not unheard of for projects which embed Lua to add "more familiar" C-style syntax such as !var and != in addition to not var and ~=. One notable project which does this is Garry's Mod, and I'm sure there are others.

Of course, using custom syntax when the normal syntax is available (or customising it in the first place) is best avoided, if possible, to avoid exactly this sort of confusion.




回答2:


It's a syntax error.

Some languages, mostly C and its relatives, use ! as a logical "not" operator, but Lua uses the not keyword instead, and does not use ! for anything as far as I know (not even as part of the inequality operator; it uses ~= where C uses !=).

You appear to have gotten hold of some Lua code written by someone who doesn't know that.



来源:https://stackoverflow.com/questions/21766643/what-does-an-exclamation-mark-in-lua-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!