为什么脚本不能按照我写的顺序运行?

我正在按顺序编写代码,但它不像一个异步程序那样运行。

代码:

   function kontrol()
      local y = 0
      RegisterNetEvent("example")
      AddEventHandler("example", function(source,sayi)
         local x = source
         y = x

      end)
       return y
 end

该函数返回0,尽管y = x,我应该如何使该代码返回x的值?

点赞
用户1847592
用户1847592

最初 y 是零,所以在请求值之前应该异步等待。

function kontrol()
   local y = 0
   RegisterNetEvent("example")
   AddEventHandler("example", function(source,sayi)
      local x = source
      y = x
   end)
   return function() return y end
end

local get_y = kontrol()
-- 等待事件发生
local y = get_y()
-- 现在你有了 y

或者在 y 准备好后传递一个函数来执行某些操作。

function kontrol(f)
   local y = 0
   RegisterNetEvent("example")
   AddEventHandler("example", function(source,sayi)
      local x = source
      y = x
      f(y)
   end)
end

kontrol(
   function(y)
      -- 在这里对 y 进行某些操作
      print(y)
   end)
2020-10-05 05:06:16