Vishera
Vishera

Reputation: 127

Lua random image

I have a Lua script I am using in a tabletop game and basically you have a "token" that represents a creature. When it dies, it overlays an image (which I have indicated in an .xml script) with an image of like a blood splat, or tombstone etc.

How do I make it so it would randomize which image gets overlayed?

The Script is here.

The lines below (178-184) are the main section that tells it "put image X over the token". I want it to randomize between say, 5 different images..

if not widgetDeathIndicator then
    widgetDeathIndicator = tokenCT.addBitmapWidget("token_dead");
    widgetDeathIndicator.setBitmap("token_dead");
    widgetDeathIndicator.setName("deathindicator");
    widgetDeathIndicator.setTooltipText(sName .. " has fallen, as if dead.");
    widgetDeathIndicator.setSize(nWidth-20, nHeight-20);
end

token_dead is the name of the current image being used, which in the .xml directs to a .png

Upvotes: 0

Views: 425

Answers (1)

Jack Taylor
Jack Taylor

Reputation: 6207

Yes, you can use math.random for this.

local images = {
    'token_dead',
    'another_image_name',
    'yet_another_image_name',
}

local image = images[math.random(#images)]

math.random(n) will return a pseudo-random integer between 1 and n, so if you pass in #images (the length of the images table) you will get a valid pseudo-random table index for images.

To get better randomness you should set math.randomseed before you call math.random. (If you don't set it, then math.random will return the same sequence of "random" numbers each time.)

Upvotes: 2

Related Questions