Skip to content
  • Shop
  • About the Creator
  • Author BookShelf
  • Black Cat Adventures
  • Newsletter Options
  • Contact Us
  • Privacy Policy
  • Cookie Policy (US)
Kids Hide Away

Kids Hide Away

Specializing in Educational Software

  • Home
  • Shop
    • Free Printable Word Tracker
    • Productivity Timers
      • Productivity Timers – Black
      • Productivity Timers – Lake Erie
      • Productivity Timers – Bubbles
    • RedM Scripts (Tebex)
    • Black Cat Adventures
    • Catch FireFlies, a Free Casual PC Game
    • Stickers
      • KJ’s Cartoons
    • Digital
      • OneNote Digital Planner Stickers – Kaban Board – Authors – Write Chapters
      • Digital Planner Stickers – Publishing Milestones for Authors
      • OneNote Digital Planner Sticker – Kaban Board – Authors – Edit Chapter
    • Apps
      • Space Nebula Timer App (Linux)
      • Space Nebula Timer App (Windows)
      • Forest Timer App (Windows)
      • Forest Timer App (Linux)
      • Big and Bold Timer App (Linux)
      • Big and Bold Timer App (Windows)
      • Bubbles Timer App (Windows)
      • Runes Timer App (Windows)
      • Bubbles Timer App (Linux)
      • Runes Timer App (Linux)
      • Sunset Forest Timer App (Linux)
      • Sunset Forest Timer App (Windows)
  • Indie Game Studio
    • The Wild Ones
    • The Drained
    • CFX/REDM
      • Barrels Version 2
      • Barrels Version 1
      • Crates Version 2
      • Crates Version 1
      • Dressers Version 1
      • Footlocker Version 1
      • Desks Version 1
      • Cupboards Version 1
      • Valentine Green House
    • Ice Hockey Games
      • Hat Trick – Connect 3
      • Power Play – Endless Runner
      • Dream Team – Fantasy Statistics
      • Ice Hockey Games – Practice Skills
      • Offsides – RPG
      • Ice Hockey Games – Tournament Games
    • Capture FireFlies
    • Black Cat Adventures
      • Black Cat Adventures
      • Black Cat Adventures
      • Black Cat Adventures – Manual
      • Black Cat Adventures – Statistics
      • Black Cat Adventures – Demo
    • 2D Games
      • Classic Arcade Games
      • Space Race
    • Educational Games
  • Blog
    • About the Creator
  • Life Long Learner
    • Packt: Python Books
    • Udemy: Python
    • Udemy: C#
    • Udemy: C++
    • Udemy: Android
    • Udemy: Unreal
    • Packt: node.js Books
    • 3ds Max Modeling for Games by Andrew Gahan
  • Recent Courses
    • Domestika: Architectural Sketching with Watercolor and Ink (Project Board)
    • Domestika: Colored Marker Techniques for Manga (Project Board)
    • Domestika: Narrative Techniques for Illustrated Stories (Project Board)
    • Domestika: Watercolor Coloring for Comics and Illustrations
    • Domestika: Urban Sketching: Express Your World in a New Perspective (Project Board)
    • Domestika: Pictorial Sketchbook with Gouache (Project Board)
    • Domestika: Introduction to Colour Psychology: Chromatic Narrative
    • Domestika: Watercolor Techniques for Dreamlike Illustrations
    • Domestika: Illustrated Stories: From Idea to Paper
    • Domestika: Illustration Techniques with Watercolor and Gouache (Project Board)
    • Domestika: Creative Sketching: Fill Your Illustrations with Life and Detail (Project Board)
    • Teachable: HB 90 by Sarra Cannon @ Hearth Breathings
    • Teachable: Publish and Thrive by Sarra Cannon @ Hearth Breathings
    • Teachable: Lindsey the Frugal Crafter
    • Teachable: Alcohol Markers by Lindsey the Frugal Crafter
  • Indie Artist
    • Inktober
      • How to make a comic in 6 days – Day 1
      • How to make a comic in 6 days – Day 2
      • How to make a comic in 6 days – Day 3
      • How to make a comic in 6 days – Day 4
      • How to make a comic in 6 days – Day 5
      • How to make a comic in 6 days – Day 6
  • Author BookShelf
    • Alexander’s Bounty
    • Rebecca’s Scroll
    • Author
  • Melvin’s Games
  • SNHU
    • SNHU: GAM303
    • SNHU: IT140
    • SNHU: GAM305
    • SNHU: GAM415
    • SNHU: GAM465
    • SNHU: GAM495
    • SNHU: GAM312
    • SNHU: GAM207
    • SNHU: GRA220
    • SNHU: GRA211
    • SNHU: GRA310
    • SNHU: IT145
    • SNHU: IT230
    • SNHU: IT312
    • SNHU: IT328
    • SNHU: IT450
    • SNHU: MAT225
    • SNHU: COM-230
    • SNHU: GRA202
  • Contact Us
  • Toggle search form
REDM FAQs

How do I do random in RedM/CFX/Lua?

Posted on October 9, 2022January 21, 2023 By Southworth Family

A: The simplest random (keeping in mind that no programming language or computer can ever truly be random) is to use a timestamp for a seed. Here’s an example of a client-side Lua script for RedM/CFX.

-- create a random seed using the game timmer
local random_seed_ = GetGameTimer()   
-- display if your curious
print("GetGameTimer:", random_seed_)  
-- generate the random seed that the "math.random" uses
math.randomseed(random_seed_)
-- generate your random in a number range. 
-- minimum set to 1, and max set to 10
random_int = math.random( math.tointeger(1), math.tointeger(10))  

Q: That’s cool and all but how do I use that practically?

A: Okay well let’s say you have an array of items and you want to randomly choose items from that array.

local random_seed_ = GetGameTimer() 
print("GetGameTimer:", random_seed_)  
math.randomseed(random_seed_)
-- above is same as before but here we switch 
--- to pull the max of an array Config.models
random_int = math.random( math.tointeger(1), math.tointeger(#Config.models))
 

Q: Ok, that’s more use full but how do I really get a random selection from an array?
For example, I want a better random selection of rewards for my players.

A: Alrighty then. Here we go. You will want a multi-blind random. By multi, I mean 2 or more.

You need to have your original array of items.

Then select the random max using the above random example.

Then create a new array, and copy the items that are in 1 to your random max to the new array.

Then do those same steps again using your new array.

Do this a couple of times before you generate your random number and pull one or two items from the array to reward the player.

Each time you do this you should get a very different item array to choose from in the end.

Insert code example later.

Now in my scripts, I pull the original items from a database, based on their category. Then I can do this process on each type. Then for the final reward, I pull items from each array, so the player gets a variety of rewards each time. For example, the seed_collector script gives fruit, plants, and seeds.

Okay now we took this another step and used MIT’s epoch with GetPosixTime To get an even better seed.

-- The MIT License (MIT)
-- Copyright (c) 2018,2020 Thomas Mohaupt <thomas.mohaupt@gmail.com>

-- year: 2-digit (means 20xx) or 4-digit (>= 2000)
function datetime2epoch(second, minute, hour, day, month, year)
    local mi2sec = 60
    local h2sec = 60 * mi2sec
    local d2sec = 24 * h2sec
    -- month to second, without leap year 
    local m2sec = {
          0, 
          31 * d2sec, 
          59 * d2sec, 
          90 * d2sec, 
          120 * d2sec, 
          151 * d2sec, 
          181 * d2sec, 
          212 * d2sec, 
          243 * d2sec, 
          273 * d2sec, 
          304 * d2sec, 
          334 * d2sec }  
          
    local y2sec = 365 * d2sec
    local offsetSince1970 = 946684800
  
    local yy = year < 100 and year or year - 2000
  
    local leapCorrection = math.floor(yy/4) + 1  
    if (yy % 4) == 0 and month < 3 then
      leapCorrection = leapCorrection - 1
    end
    
    return offsetSince1970 + 
          second + 
          minute * mi2sec + 
          hour * h2sec + 
          (day - 1) * d2sec + 
          m2sec[month] + 
          yy * y2sec +
          leapCorrection * d2sec 
  end

Then we use this to generate our random number for our random seed.

function RandomwithNewSeed(randomMin, randomMax)
	local strt_year, strt_month, strt_day, strt_hour, strt_minute, strt_second = GetPosixTime()
	local _epoc = datetime2epoch(strt_second, strt_minute, strt_hour, strt_day, strt_month, strt_year)   
	math.randomseed(math.tointeger(_epoc))
	local random_num = math.random(math.tointeger(randomMin), math.tointeger(randomMax))    
	return(random_num)
end 

Note this only works on the client side. To get it to work on the server side your client would need to pass the epoc time variable to the server (variable). To combat potential nil issues I included an error check that defaults to pi if epoc is missing.

function SERVER_RandomwithNewSeed(randomMin, randomMax, _epoc)  
      if _epoc == nil then 
            _epoc = (3.141592653589793238*1000) 
            if(Config.debug== 1) then  print("_epoc (nil) ",_epoc) end 
      else
            if(Config.debug== 1) then  print("_epoc ",_epoc) end 
      end 
	math.randomseed(math.tointeger(_epoc))
	local random_num = math.random(math.tointeger(randomMin), math.tointeger(randomMax))   
	return(random_num)
end 

Hits: 75

Blog, CFX/REDM, Daily Code Highlights, Dev-Log, Engines, Game Categories, Indie Game Studio, RP Games, VORP-OpenSource, Work In Progress Tags:array, cfx, cfxserver, crimson creek, crimsoncreek, database, install, integer, mods, opensource, path, rdo, rdr, redm, table, vorp, vorpcore

Post navigation

Previous Post: How to make a comic in 6 days – Day 6
Next Post: Barrels Version 1

Related Posts

HB90 – Nov 17th – NaNoWrimo – Wednesday- Blog Author Topics
O3de FAQs O3DE WASD stops working in the edtior window. Blog
REDM FAQs Day 9 – RedM/CFX/VORP Project – (Done) The bank doors are locked. The banker is inside. Blog
Dev Log – Ice Hockey Themed Connect 3 – Jun 1st – Part 8 Blog
REDM FAQs How do I change the “Oh I found” message? ForagePlants CFX/REDM
REDM FAQs Day 7 – RedM/CFX/VORP Project – How do I force the client to use a specific build? Blog

Scripts can be purchased at ✨✨tebex✨✨

Blog Categories

  • Author Topics (58)
  • Blog (224)
  • Clark and Parker Academy (6)
  • FAQ (5)
  • Games We Play (17)
  • Home School (1)
  • Homestead and Gardens (4)
  • Indie Artist (34)
  • Indie Game Studio (117)
  • Life Adventures and Memories (8)
  • Life Long Learner (1)

New Products

  • Dark Mode - Weekly Hourly Page - Digital - Undated - Letter Size
    Dark Mode - Weekly Hourly Page - Digital - Undated - Letter Size
  • Light Mode - Weekly Hourly Page - Digital - Undated - Letter Size
    Light Mode - Weekly Hourly Page - Digital - Undated - Letter Size
  • Cozy Mystery Digital Templates for Authors
    Cozy Mystery Digital Templates for Authors
  • Game Development Digital Planner Page for Projects
    Game Development Digital Planner Page for Projects
  • Digital Planner Stickers - Publishing Milestones for Authors
    Digital Planner Stickers - Publishing Milestones for Authors
  • OneNote Digital Planner Sticker - Kaban Board - Authors - Edit Chapter
    OneNote Digital Planner Sticker - Kaban Board - Authors - Edit Chapter
  • OneNote Digital Planner Stickers - Kaban Board - Authors - Write Chapters
    OneNote Digital Planner Stickers - Kaban Board - Authors - Write Chapters
  • Sunset Forest Timer App (Windows)
    Sunset Forest Timer App (Windows)

Events

Subscribe to our newsletter!


Featured Books

Alexander’s Bounty

Alexander’s Bounty

August 1920 Cleveland, Ohio. Detective Alexander Jones

More info →

Rebecca’s Scroll

Rebecca’s Scroll

August 1920 Cleveland, Ohio. Bookstore owner and conservation specialist Rebecca Williams struggles to clear her name after she finds a body in the museum's bronze age gallery. Amid a flood of exhausting police interviews, missing artifacts, angry crowds, magical puzzles, sneaky suspects, and death threats. Will she be the next victim or begin the next great adventure?

More info →

Contact US

Scripts can be purchased at ✨✨tebex✨✨

For assistance, please create a support ticket on our 🎟️🎟️website 🎟️🎟️

Please use the email address you purchased the script with to create the support ticket and account.

[Dragon Code - 💬💬DISCORD💬💬]

[PATREON 🎨🎨KLSANDELS 🎨🎨] for new server installs, custom code requests, tutorials, and early access to scripts and servers.

Game Server List: 👾 🕹️ 💻 Crimson Creek 💻🕹️👾

[Crimson Creek - 💬💬 DISCORD 💬💬]

[DISCORD RULES] – Be polite, professional, and patient in your communications with staff, dev, and the general community.

Copyright © 2023 Kids Hide Away.

Powered by PressBook Masonry Dark

Loading...
Manage Cookie Consent
We use cookies to optimize our website and our services. They are not required for the site to function.
Functional cookies Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage vendors Read more about these purposes
View preferences
{title} {title} {title}
 

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.