如何在不覆盖模块名称的情况下使用变量名称?

math.random()是开箱即用的,但是如果我将math设置为其他值,则会出现错误

local math = 1 + 1 -- 将math设置为其他 math.random() -- 出错

有没有办法在设置local math = 1 + 1的情况下仍然使math.random()工作?

我有很多带点函数的模块,例如coord.get()offset.get()

但是这些基本单词如coordoffset变得无法用于变量名称,这很令人恼火

点赞
用户7396148
用户7396148

使用正确编写的模块,你可以这样操作 local coords = require("coord")

这将创建一个本地变量coords,当后面出现本地定义并覆盖coord时,你仍然可以通过coords访问函数。如果模块未返回它创建的表格,并将其设置为全局变量,那么这将不起作用。

同样,如果在local math变量之前定义了它,那么对于 math.random,这也会起作用 local random = math.random

local random = math.random
local math = 1 + 1

print(random(math))

或者,你可以将整个库放入本地变量中,例如:

local maths = math
local math = 1 + 1

print(maths.random(math))

也就是说,一个名为 math 的数字变量不太可能具有良好的命名。例如,给你的例子起一个更合适的名字,如 product

2019-07-19 13:20:40
用户107090
用户107090

你总是可以再次要求模块:

require("math").random()

由于模块已经被加载,因此这不是很昂贵的。

2019-07-19 14:37:20