如何使用Lua for Corona SDK随机生成数字

臣民

我有一个简单的游戏,可以从中产生数学问题,但是效率很低,因为我必须自己亲自解决所有问题。

有谁比这更好地了解一些代码,或者将我引向一篇很好的教程,介绍如何进行设置?谢谢你。

local M = {}

M["times"] = {
    {
        question="6 x 5",  --The question.
        answers={"30", "11", "29", "20"},  --Array of possible answers.
        answer=1   --Which one from the above array is the correct answer.
    },
}

return M

更新:

{
    a = math.random( 1, 20 ),
    b = math.random( 1, 20 ),
    question = a * b,
    answer = math.random( m, n )
}

我以为这可以用,但是我在控制台中收到此错误:

mathQuestions.lua:55: attempt to perform arithmetic on global 'a' (a nil value)

更新#2

--mathQuestions.lua
M["times"] = {

    local rnd = function (x) return math.random(1,x) end
    M.times = {}
    local numQuestions = 10 -- how many questions in your database
    for i=1,numQuestions do
        local obj =
        {
            left=math.random(1,10),
            right=math.random(1,10),
            answers={rnd(100), rnd(100), rnd(100), rnd(100)},
            answerIndex=rnd(4) -- will override answer[answerIndex] later
        }
        obj.answer = obj.left * obj.right
        obj.answers[obj.answerIndex] = obj.answer
        M.times[i] = obj
    end

}

我收到此错误:

ERROR: Failed to execute new ( params ) function on 'game'

mathQuestions.lua:121: unexpected symbol near 'local'

奥立佛

试试这个:

local rnd = function (x) return math.random(1,x) end
M.times = {}
local numQuestions = 10 -- how many questions in your database
for i=1,numQuestions do
    local obj =
    {
        left=math.random(1,10),
        right=math.random(1,10),
        answers={rnd(100), rnd(100), rnd(100), rnd(100)},
        answerIndex=rnd(4) -- will override answer[answerIndex] later
    }
    obj.answer = obj.left * obj.right
    obj.answers[obj.answerIndex] = obj.answer
    M.times[i] = obj
end

唯一棘手的部分是obj.answer:您无法在表定义内进行乘法运算(例如answer = a*b在更新的问题中),因为左右(a和b)是不存在的全局变量,并且如果这样做了,answer = obj.a*obj.b那么您还可以obj尚不存在的问题(尚未创建)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章