I’m pretty new to scripting or coding and I’m trying to figure out a way to have an input that can be between 1 and 100 without having to write 100 lines of code. I am doing this in Lua and I will include my current lines below.
elseif input.text == '>coins add 100' then coins = coins + 100; print ("coins effected. "..coins)
elseif input.text == '>coins add 200' then coins = coins + 200; print ("coins effected. "..coins)
elseif input.text == '>coins add 300' then coins = coins + 300; print ("coins effected. "..coins)
I’m using this for a game I’m developing because i thought it would be a good way to practice. This in specific is for a console to change different values for debugging. Tell me if this doesn’t make sense and i will try to fix it.
Thanks!
The function that limits a number in a certain range usually called Clamp.
function math.Clamp(val, min, max)
return math.min(math.max(val, min), max)
end
It's basically and literally a math.max with math.min together.
To avoid 100 if statements, I suggest you to make a script to wait for >coins add and then ask for a number specifically.
[Edit] Apparently it doesn't allow you to do so, so here is a walkaround:
local num = string.sub(input.text, 12) -- remove 12 first characters from the string, this will leave a number in it
num = tonumber(num) -- convert a string into Lua number
if not num then -- if the conversion failed, stop the script, print the text
print("Not a number")
return
end
num = math.Clamp(num, 1, 100) -- Limit the number from 1 to 100
coins = coins + num -- add that number
print ("coins effected. " .. coins) -- New amount of coins
Related
I need to make a trolleybus number, which won't repeat for game. For example, there is a number "101" and there musn't be more "101". How to do that? I have a code, but I know, he won't work and I won't test it lol
function giveNumber()
local number = math.random(100, 199)
local takedNumbers = {}
local i = 0
local massiv = i+1
script.Parent.pered.SurfaceGui.TextLabel.Text = number
script.Parent.zad.SurfaceGui.TextLabel.Text = number
script.Parent.levo.SurfaceGui.TextLabel.Text = number
script.Parent.pravo.SurfaceGui.TextLabel.Text = number
takedNumbers[massiv] = {number}
end
script.Parent.Script:giveNumber() // what I wrote here? idk...
if number == takedNumbers[massiv] then
giveNumber()
end
i didn't test it, because I think it won't work because this code is something bad
I think this will serve your needs.
In the function generateUniqueNumber, the script loops until it found a number that is not yet in the array. (in other words, that it hasn't given out yet)
Once it found that number, it will insert it into the table to remember that it has given it out, and then it will return the number.
Then on the bottom of the script we just give the numbers to the buses :-)
--[[
Goal: Give all buses a unique number
]]
-- Variables
local takenNumbers = {};
-- This function returns a random number in the range [100, 199] that has not been taken yet
function generateUniqueNumber()
local foundNumber = false;
while not foundNumber do
randomNumber = math.random(100, 199);
if not table.find(takenNumbers, randomNumber) then
table.insert(takenNumbers, randomNumber);
return randomNumber;
end
end
end
-- This function sets the number of the bus
script.Parent.pered.SurfaceGui.TextLabel.Text = tostring(generateUniqueNumber());
script.Parent.zad.SurfaceGui.TextLabel.Text = tostring(generateUniqueNumber());
script.Parent.levo.SurfaceGui.TextLabel.Text = tostring(generateUniqueNumber());
script.Parent.pravo.SurfaceGui.TextLabel.Text = tostring(generateUniqueNumber());
2 things:
I didn't test this code as Roblox is not installed on the pc I'm currently on.
Please try formatting your code nicely next time. It greatly improves the readability! For example, you can use this website:
https://codebeautify.org/lua-beautifier
Simpler
Fill a table with free numbers...
local freenumbers = {}
for i = 1, 99 do freenumbers[i] = i + 100 end
...for every new takennumbers use table.remove() on freenumbers
local takennumbers = {}
if #freenumbers > 0 then
takennumbers[#takennumbers + 1] = table.remove(freenumbers, math.random(1, #freenumbers))
end
sorry for asking this question but I couldn't understand it
-- but i don't understand this code
ballDX = math.random(2) == 1 and 100 or -100
--here ballDY will give value between -50 to 50
ballDY = math.random(-50, 50)
I don't understand the structure what is (2) and why it's == 1
Thank you a lot
math.random(x) will randomly return an integer between 1 and x.
So math.random(2) will randomly return 1 or 2.
If it returns 1 (== 1), ballDX will be set to 100.
If it returns 2 (~= 1), ballDX will be set to -100.
A simple way to make a 50-50 chance.
That is a very common way of assigning variables in Lua based on conditionals. It’s the same you’d do, for example, in Python with “foo = a if x else b”:
The first function, math.random(2), returns either 1 or 2. So, if it returns 1 the part math.random(2) == 1 is true and so you assign 100 to the variable ballDX. Otherwise, assign -100 to it.
In lua
result = condition and first or second
basically means the same as
if condition and first ~= nil and first ~= false then
result = first
else
result = second
end
So in your case
if math.random(2) == 1 then
ballDX = 100
else
ballDX = -100
end
in other words, there is a 50/50 chance for ballDX to become 100 or -100
For a better understanding, a look at lua documentation helps a lot :
https://www.lua.org/pil/3.3.html
You can read:
The operator or returns its first argument if it is not false; otherwise, it returns its second argument:
So if the random number is 1 it will return the first argument (100) of the "or" otherwise it will return the second argument (-100).
I'm writing a game using Corona SDK in lua language. I'm having a hard time coming up with a logic for a system like this;
I have different items. I want some items to have 1/1000 chance of being chosen (a unique item), I want some to have 1/10, some 2/10 etc.
I was thinking of populating a table and picking a random item. For example I'd add 100 of "X" item to the table and than 1 "Y" item. So by choosing randomly from [0,101] I kind of achieve what I want but I was wondering if there were any other ways of doing it.
items = {
Cat = { probability = 100/1000 }, -- i.e. 1/10
Dog = { probability = 200/1000 }, -- i.e. 2/10
Ant = { probability = 699/1000 },
Unicorn = { probability = 1/1000 },
}
function getRandomItem()
local p = math.random()
local cumulativeProbability = 0
for name, item in pairs(items) do
cumulativeProbability = cumulativeProbability + item.probability
if p <= cumulativeProbability then
return name, item
end
end
end
You want the probabilities to add up to 1. So if you increase the probability of an item (or add an item), you'll want to subtract from other items. That's why I wrote 1/10 as 100/1000: it's easier to see how things are distributed and to update them when you have a common denominator.
You can confirm you're getting the distribution you expect like this:
local count = { }
local iterations = 1000000
for i=1,iterations do
local name = getRandomItem()
count[name] = (count[name] or 0) + 1
end
for name, count in pairs(count) do
print(name, count/iterations)
end
I believe this answer is a lot easier to work with - albeit slightly slower in execution.
local chancesTbl = {
-- You can fill these with any non-negative integer you want
-- No need to make sure they sum up to anything specific
["a"] = 2,
["b"] = 1,
["c"] = 3
}
local function GetWeightedRandomKey()
local sum = 0
for _, chance in pairs(chancesTbl) do
sum = sum + chance
end
local rand = math.random(sum)
local winningKey
for key, chance in pairs(chancesTbl) do
winningKey = key
rand = rand - chance
if rand <= 0 then break end
end
return winningKey
end
I am trying to put together a lua script to be called from Redis (via an EVAL call) in order to return every other nth element of a sorted set (nth being the rank in the set, not the score).
There are very few online examples of Lua scripts that can be used to build upon, would anyone be able to point me in the right direction?
local function copyNOtherElements(table, interval, startpos)
local elemno = 1
local rettab = {}
for k, v in ipairs(table) do
if k >= startpos and (k - startpos) % interval == 0 then
rettab[elemno] = v
elemno = elemno + 1
end
end
return rettab
end
Sorry about formatting, typing on a phone. that's assuming the table is a 1 based array
For future readers, adding Redis into the previous answer, and a bit more efficient code to iterate the Nth elements:
local function zrange_pick(zset_key, step, start, stop)
-- The next four lines can be removed along with the start/stop params if not needed as in OP Q.
if start == nil than
start = 0
if end == nil than
end = -1
local set_by_score = redis.call('ZRANGE', zset_key, start, end)
local result = {}
for n = 1, #set_by_score, step do
table.insert(result, set_by_score[n])
end
return result
end
I have done lots of research on invetory system for point and click game in Lua and corona.
I have come across this example,I am doing something similar to this,but I need a dynamic inventory system.
I mean if I have 4 slots,and all them are full the fifth object go to next slot,so there will be an arrow to the right so I can click on ;and go to the next page.
And imagine there are 5 items,and I have 4 slots,the fifth slot would be on the next page.
I use the third item,and third slot would then be empty,so I want the fourth and fifth item automatically move back to third and fourth slot.
I have hard time figuring this out.
Thanks for advance.
local myInventoryBag={}
local maxItems = 10 -- change this to how many you want
myInventoryBag[5]=3 -- Hammer for instance
myInventoryBag[4]=7 -- A metal Pipe for instance
local function getImageForItem(thisItem)
local itemNumber = tonumber(thisItem)
local theImage=""
if itemNumber==3 then
theImage="hammer.png"
elseif itemNumber == 7 then
theImage="metalpipe.png"
elseif ... -- for other options
...
else
return nil
end
local image = display.newImage(theImage)
return image
end
local function displayItems()
local i
for i=1,#myInventoryBag do
local x = 0 -- calculate based on the i
local y = 0 -- calculate based on the i
local image = getImageForItem(myInventoryBag[i])
if image==nil then return end
image.setReferencePoint(display.TopLeftReferencePoint)
image.x = x
image.y = y
end
end
local itemImages =
{
[0] = display.newImage('MISSING_ITEM_IMAGE.PNG'),
[3] = display.newImage('hammer.png'),
[7] = display.newImage('metalpipe.png'),
}
function getImageForItem(itemId)
return itemImages[itemId] or itemImages[0]
end
local myInventoryBag={}
local maxItems = 10 -- change this to how many you want
local visibleItems = 4 -- show this many items at a time (with arrows to scroll to others)
-- show inventory items at index [first,last]
local function displayInventoryItems(first,last)
local x = 0 -- first item goes here
local y = 0 -- top of inventory row
for i=first,last do
image = getImageForItem(myInventoryBag[i])
image.x = x
image.y = y
x = x + image.width
end
end
-- show inventory items on a given "page"
local function displayInventoryPage(page)
page = page or 1 -- default to showing the first page
if page > maxItems then
-- error! handle me!
end
local first = (page - 1) * visibleItems + 1
local last = first + visibleItems - 1
displayInventoryItems(first, last)
end
myInventoryBag[5] = 3 -- Hammer for instance
myInventoryBag[4] = 7 -- A metal Pipe for instance
displayInventoryPage(1)
displayInventoryPage(2)
Basically what you would do is loop through all the inventory slots and check if the slot is empty. If it's empty, place the item in that slot and stop the loop. If it's not, go to the next one.
If you want to remove an item from the inventory, you can simply call table.delete(myInventoryBag, slotToEmpty).
For pages, you'd simply have a page variable. When drawing the inventory slots, just loop from slots (page-1) * 4 + 1 to page * 4.
(Edit: I'd highly recommend using proper indentation, as it will make the code much much more readable.)