0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

luajitでは固定シードなのにプロセスごとに別の値を返すことがある(lume.weightedchoice)

Posted at

lume.weightedchoiceは{値1 = 割合1, 値2 = 割合2, ..}という引数を与えると、割合に応じた値を返す関数です。
引数の与え方がなんか変ですが、理解したので使っていました。

しかし、週末レイトレーシングをやって一フレームごとに出力してアニメーションを作ろうとしたら、ランダムで配置したボールの色や材質が変わってしまうという現象に遭遇しました。

random_scene.png

検証コード

luaはテーブルの順序を記憶しない仕様です。よってweightedchoice内で調べる順序も決まっていません。
このことが原因で起動するたびに別の値を出してしまいます。

.lua
local lume = require 'lume'
math.randomseed(1)

t = {abc = 35, def = 30, ghi = 35}

for _=1,10 do
	print(lume.weightedchoice(t))
end

luajit、lua5.4の両方で起動のたびに違う並びになることが確認できます。

回避方法

配列を与えれば順序は決まっているので、以下のようにします。

.lua
-- lume.weightedchoice({['A'] = 50, ['B'] = 30, ['C'] = 10})

rawget({'A', 'B', 'C'}, lume.weightedchoice({50, 30, 10}))

感想

全く同じコードが(固定シードにしたのに)別の動作をする現象を見たのははじめてでした。
一枚絵を生成している時は気づきませんでした。

a.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?