lua 游戏开发(逻辑运算符) 自动门实例

bool

false

有且仅有false 和nil 。

ture

除了以上两者其他都为真,0 也是true。

and or

lua 里的and和or更像是c里的三目运算符( : ? )

and

若 A 为 false,则返回 A,否则返回 B。

or

若 A 为 ture,则返回 A,否则返回 B。

and的优先级高于or
cur > n and -0.2 or 0.2就是c语言中的cur > n ? -0.2 :0.2

nil

假始定义一个本地变量
local example
print( example)
因为没给examp赋值,example默认是无效的,所以将会输出nil

not

取反,常用 not player 等语句中作为安全条件

若x无赋初值,但又需要做安全检查
往往会这样写
if not x then
x = y
end
可以写为
x=x and y

附一个roblox的自动门实例

local door = {
     }     --一个table
local d1,d2 = script.Parent.d1,script.Parent.d2--同组下的d1,d2两个part
door[d1],door[d2] = d1.CFrame,d2.CFrame--往里存d1,d2的位置向量
--for d,cf in pairs(door) do  --d是d1 ,d2,cf是1.CFrame,d2.CFrame

local open = (d1.Size.x-0.2)	-- 开门方向的位移
local tag = 0			-- Used to serialize the GoTo function
local cur = 0			-- Current opening. Used to determine current opening when door is triggered while closing
local last = 0			-- Debounce (time-based) for Trigger part
                        --作为记录值的工具
local trig = script.Parent.Trigger	-- 在门中心有一个part 正方形,透明,无碰撞,用来判断是否有人碰到来开门 

local CF = CFrame.new
--print("cf=")	
--print(CF)
--未设置随机种子,经过测试都不一样
-- 'Optimization' for new CFrame

function GoTo(n,noRepeat)	-- NOTE: Lua 5.2+ uses a 'goto' function. This function has nothing to do with that.
	                       --noRepreat未定义,默认为nil
	local myTag = time() --time()返回游戏开局到现在所走过的时长,约0.3更新一次(动态)
	tag = myTag
	
	----- Main loop to change door location-----
	for i = cur,n,(cur > n and -0.2 or 0.2) do	--(条件 and 返回1 or 返回2)类似于三目运算符?:
		                                          --可用于移动+复原
		if (tag ~= myTag) then return end  --tag和mytag相等-false,不等-true
		cur = i
		for d,cf in pairs(door) do  --for 对象,数值 in pairs(数组)do
			d.CFrame = (cf*CF(i,0,0))	-- Change CFrame relative to its original placement
			                           --==等于两步实现d1.cframe=(d1.cframe*cf(cur,0,)
		end
		wait()
	end
	for d,cf in pairs(door) do	-- Security loop to patch up gap due to unfinished loop goal (when the loop's step doesn't allow it to fully reach the loop goal)
		d.CFrame = (cf*CF(n,0,0))
	end
	wait(2)
	if (not noRepeat and tag == myTag) then	--not布尔值即取反,not nil即true
		                                      -- Only used when this function is used to open the door to trigger that it should close
		GoTo(0,true)

	end
end

do	-- Set up the Trigger part (make it large enough to detect players)
	local c = trig.CFrame
	local sz = ((d1.Size.x*2)+2)
	trig.Size = Vector3.new(sz,(d1.Size.y+2),sz)
	trig.CFrame = c
end

-- Set up the trigger event
script.Parent.Trigger.Touched:connect(function(obj)
	if (game.Players:GetPlayerFromCharacter(obj.Parent)) then--GetPlayerFromCharacter(obj)如果不是玩家返回一个nil,此处效果判定接触对象是不是玩家
		local t = time() 
		--print(t)
		if ((t-last) < 1) then return end	-- 1-second debounce (time-based)
		last = t
		GoTo(open)
	end
end)

你可能感兴趣的:(lua,游戏开发,游戏)