lua学习笔记--random function
2014-05-23 00:08
501 查看
今天看到lua数学库中random
math.random有3种调用方式:
1:不带参数,返回[0,1]之间的实数类型的随机数
2:带1个参数n,返回的是[1,n]的随机数
3:带2个参数m和n,返回的是[m,n]之间的随机数
一般还会配合随机化种子函数math.randomseed(os.time())使用
eg:随机生成5个[1,10]数
math.randomseed(os.time()) //这里不要放入for循环中,如果放在循环中则会生成的数都是一样。
local rand=math.random
for i=1,5 do
local x=rand(1,10)
print(x)
end
这个结果会生成5个随机数,但细心一点则会发现每次运行第一个数都没有改变。因此需要把第一个数移除,这样就有点算随机了。
方法1:
tb={}
math.randomseed(os.time())
local rand=math.random
for i=1,6 do
local x=rand(1,10)
tb[i]=x --生成的数直接放入表中
end
table.remove(tb,1) --移除第一项方法2:用一张新表把旧表里面需要的元素都插入到新表中
tb1={}
for i,v in pairs(tb) do
if i~=1 then
table.insert(tb1,v)
end
end
math.random有3种调用方式:
1:不带参数,返回[0,1]之间的实数类型的随机数
2:带1个参数n,返回的是[1,n]的随机数
3:带2个参数m和n,返回的是[m,n]之间的随机数
一般还会配合随机化种子函数math.randomseed(os.time())使用
eg:随机生成5个[1,10]数
math.randomseed(os.time()) //这里不要放入for循环中,如果放在循环中则会生成的数都是一样。
local rand=math.random
for i=1,5 do
local x=rand(1,10)
print(x)
end
这个结果会生成5个随机数,但细心一点则会发现每次运行第一个数都没有改变。因此需要把第一个数移除,这样就有点算随机了。
方法1:
tb={}
math.randomseed(os.time())
local rand=math.random
for i=1,6 do
local x=rand(1,10)
tb[i]=x --生成的数直接放入表中
end
table.remove(tb,1) --移除第一项方法2:用一张新表把旧表里面需要的元素都插入到新表中
tb1={}
for i,v in pairs(tb) do
if i~=1 then
table.insert(tb1,v)
end
end
相关文章推荐
- lua学习笔记之Lua的function、closure和upvalue
- Lua学习笔记(七) 函数function简介
- 学习笔记☞ python 基础(python3)【四】(函数 function,None,return,列表-2,random模块)
- Lua学习笔记之function type
- lua学习笔记---Function(函数)
- redis lua脚本学习笔记math.random()获取随机数
- Lua 学习笔记之 function、closure和upvalue
- lua学习笔记之Lua的function、closure和upvalue
- LUA学习笔记2-Iterators and the Generic for
- Lua学习笔记一
- LUA学习笔记3 - Compilation, Execution, and Errors
- [LUA学习笔记04]Lua语法--数据类型
- Lua入门系列----pil学习笔记之Type and Values (2)
- LUA学习笔记(1)
- Lua入门系列----pil学习笔记之Getting Start
- Lua入门系列----pil学习笔记之 Type and Values (1)
- Lua入门系列----pil学习笔记之Getting Start
- Lua入门系列----pil学习笔记之 Type and Values (1)
- Lua学习笔记四--返回值和UserData
- Lua学习笔记一