如何用 Lua 种语言编写保存随机数的文件
How to write file for save a random number by Lua languages
这是我的功能
function randomNum2(num)
f = io.open("result.csv", "a+")
num = math.randomseed(os.clock()*100000000000)
f:write(string.format("%s\n", num))
f:close()
return "TETB"..(math.random(1000000000))
end
result.csv
文件的输出类似。
nil
nil
nil
nil
nil
nil
nil
nil
nil
我想知道如何像这样将随机数保存到 result.csv
文件。
TETB539286665
TETB633918991
TETB892163703
TETB963005226
TETB359644877
TETB131482377
关于问题是什么以及如何解决它有什么想法吗?谢谢。
math.randomseed
函数没有 return 任何东西,它只是将 math
库设置为使用某个数字作为“随机”数字的基础,您应该使用运行 math.randomseed
之后的 math.random
函数配置库,math.random
return 是一个数字,如果你不这样做,你可以指定它们之间的范围可能 return 一个浮点数。
此外,num
参数未被使用,可以将其删除或重命名为 max
,并用作 math.random
调用中的参数,作为最大结果数。
多做local
变量。
并且不要将 string
与 number
.
连接 (..)
即时将 math.random()
转换为 tostring()
。
我将您的版本更正为...
randomNum2=function()
local f = io.open("result.csv", "a+")
local rand = "TETB"..tostring(math.random(100000000000))
f:write(string.format("%s\n", rand))
f:close()
return rand
end
...并且 math.randomseed()
不是必需的。
然后你得到一个result.csv你想要的。
在交互式独立 Lua 解释器中测试...
> for i=1,10 do randomNum2() end
> os.execute('cat result.csv')
TETB73252732829
TETB48306115776
TETB83524202926
TETB53376530639
TETB39893346222
TETB60394413785
TETB97611122173
TETB35725172461
TETB48950449408
TETB15779990338
true exit 0
-- Next example puts out the return of the function.
-- That can be used without reading the file.
-- To check what was written/append to result.csv on the fly.
> print(randomNum2())
TETB73113866427
这是我的功能
function randomNum2(num)
f = io.open("result.csv", "a+")
num = math.randomseed(os.clock()*100000000000)
f:write(string.format("%s\n", num))
f:close()
return "TETB"..(math.random(1000000000))
end
result.csv
文件的输出类似。
nil
nil
nil
nil
nil
nil
nil
nil
nil
我想知道如何像这样将随机数保存到 result.csv
文件。
TETB539286665
TETB633918991
TETB892163703
TETB963005226
TETB359644877
TETB131482377
关于问题是什么以及如何解决它有什么想法吗?谢谢。
math.randomseed
函数没有 return 任何东西,它只是将 math
库设置为使用某个数字作为“随机”数字的基础,您应该使用运行 math.randomseed
之后的 math.random
函数配置库,math.random
return 是一个数字,如果你不这样做,你可以指定它们之间的范围可能 return 一个浮点数。
此外,num
参数未被使用,可以将其删除或重命名为 max
,并用作 math.random
调用中的参数,作为最大结果数。
多做local
变量。
并且不要将 string
与 number
.
连接 (..)
即时将 math.random()
转换为 tostring()
。
我将您的版本更正为...
randomNum2=function()
local f = io.open("result.csv", "a+")
local rand = "TETB"..tostring(math.random(100000000000))
f:write(string.format("%s\n", rand))
f:close()
return rand
end
...并且 math.randomseed()
不是必需的。
然后你得到一个result.csv你想要的。
在交互式独立 Lua 解释器中测试...
> for i=1,10 do randomNum2() end
> os.execute('cat result.csv')
TETB73252732829
TETB48306115776
TETB83524202926
TETB53376530639
TETB39893346222
TETB60394413785
TETB97611122173
TETB35725172461
TETB48950449408
TETB15779990338
true exit 0
-- Next example puts out the return of the function.
-- That can be used without reading the file.
-- To check what was written/append to result.csv on the fly.
> print(randomNum2())
TETB73113866427