0

This is my function

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

The output from result.csv file like.

nil
nil
nil
nil
nil
nil
nil
nil
nil

I would like to know how to save a random number to result.csv file like this.

TETB539286665
TETB633918991  
TETB892163703  
TETB963005226  
TETB359644877  
TETB131482377  

Any ideas on what the problem is and how to fix it? Thanks.

  • BTW, call `math.randomseed` *once* at the start of the program. See https://stackoverflow.com/questions/35455489/difference-between-math-random-and-math-randomseed-in-lua/35455929#35455929 – lhf Sep 07 '21 at 11:24

2 Answers2

1

The math.randomseed function doesn't return anything, it just sets the math library to use a certain number as the basis for the "random" numbers, you should use the math.random function after running math.randomseed which configures the library, math.random returns a number and you can specify a range between them, if you don't it will likely return a floating point number.

Also the num parameter is not being used and can be removed or renamed to max and used as an argument in the math.random call to serve as the maximum result number.

0

Do more local variable.
And do not concat (..) a string with a number.
Convert math.random() with tostring() on the fly.
I corrected your version to...

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

...and math.randomseed() is not necessary.

Then you get a result.csv with what you want.
Tested in an interactive standalone Lua interpreter...

> 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
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15