/Lua/ How to do this (idk how to call that lol) - lua

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

Related

LUA: Looking for a specific table by its variable

I'm currently starting work on a text adventure game in Lua--no addons, just pure Lua for my first project. In essence, here is my problem; I'm trying to find out how I can do a "reverse lookup" of a table using one of its variables. Here's an example of what I've tried to do:
print("What are you trying to take?")
bag = {}
gold = {name="Gold",ap=3}
x = io.read("*l")
if x == "Gold" then
table.insert(bag,gold)
print("You took the " .. gold.name .. ".")
end
Obviously, writing a line like this with every single object in the game would be very... exhausting--especially since I think I'll be able to use this solution for not just taking items but movement from room to room using a reverse lookup with each room's (x,y) coordinates. Anyone have any ideas on how to make a more flexible system that can find a table by the player typing in one of its variables? Thanks in advance!
-blockchainporter
This doesn't directly answer your question as you asked it, but I think it would serve the purpose of what you are trying to do. I create a table called 'loot' which can hold many objects, and the player can place any of these in their 'bag' by typing the name.
bag = {}
loot = {
{name="Gold", qty=3},
{name="Axe", qty=1},
}
print("What are you trying to take?")
x = io.read("*l")
i = 1
while loot[i] do
if (x == loot[i].name) then
table.insert(bag, table.remove(loot,i))
else
i = i + 1
end
end
For bonus points, you could check 'bag' to see if the player has some of that item already and then just update the quantity...
while loot[i] do
if (x == loot[i].name) then
j, found = 1, nil
while bag[j] do
if (x == bag[j].name) then
found = true
bag[j].qty = bag[j].qty + loot[i].qty
table.remove(loot,i)
end
j = j + 1
end
if (not found) then
table.insert(bag, table.remove(loot,i))
end
else
i = i + 1
end
end
Again, this isn't a 'reverse lookup' solution like you asked for... but I think it is closer to what you are trying to do by letting a user choose to loot something.
My disclaimer is that I don't use IO functions in my own lua usage, so I have to assume that your x = io.read("*l") is correct.
PS. If you only ever want objects to have a name and qty, and never any other properties (like condition, enchantment, or whatever) then you could also simplify my solution by using key/val pairs:
bag = {}
loot = { ["Gold"] = 3, ["Axe"] = 1 }
print("What are you trying to take?")
x = io.read("*l")
for name, qty in pairs(loot) do
if x == name then
bag.name = (bag.name or 0) + qty
loot.name = nil
end
end
I have a few notes to start before I specifically address your question. (I just want to do this before I forget, so please bear with me!)
I recommend printing to the terminal using stderr instead of stdout--the Lua function print uses the latter. When I am writing a Lua script, I often create a C-style function called eprintf to print formatted output to stderr. I implement it like this:
local function eprintf(fmt, ...)
io.stderr:write(string.format(fmt, ...))
return
end
Just be aware that, unlike print, this function does not automatically append a newline character to the output string; to do so, remember to put \n at the end of your fmt string.
Next, it may be useful to define a helper function that calls io.read("*l") to get an entire line of input. In writing some example code to help answer your question, I called my function getline--like the C++ function that has similar behavior--and defined it like this:
local function getline()
local read = tostring(io.read("*l"))
return read
end
If I correctly understand what it is you are trying to do, the player will have an inventory--which you have called bag--and he can put items into it by entering item names into stdin. So, for instance, if the player found a treasure chest with gold, a sword, and a potion in it and he wanted to take the gold, he would type Gold into stdin and it would be placed in his inventory.
Based on what you have so far, it looks like you are using Lua tables to create these items: each table has a name index and another called ap; and, if a player's text input matches an item's name, the player picks that up item.
I would recommend creating an Item class, which you could abstract nicely by placing it in its own script and then loading it as needed with require. This is a very basic Item class module I wrote:
----------------
-- Item class --
----------------
local Item = {__name = "Item"}
Item.__metatable = "metatable"
Item.__index = Item
-- __newindex metamethod.
function Item.__newindex(self, k, v)
local err = string.format(
"type `Item` does not have member `%s`",
tostring(k)
)
return error(err, 2)
end
-- Item constructor
function Item.new(name_in, ap_in)
assert((name_in ~= nil) and (ap_in ~= nil))
local self = {
name = name_in,
ap = ap_in
}
return setmetatable(self, Item)
end
return Item
From there, I wrote a main driver to encapsulate some of the behavior you described in your question. (Yes, I know my Lua code looks more like C.)
#!/usr/bin/lua
-------------
-- Modules --
-------------
local Item = assert(require("Item"))
local function eprintf(fmt, ...)
io.stderr:write(string.format(fmt, ...))
return
end
local function printf(fmt, ...)
io.stdout:write(string.format(fmt, ...))
return
end
local function getline()
local read = tostring(io.read("*l"))
return read
end
local function main(argc, argv)
local gold = Item.new("Gold", 3)
printf("gold.name = %s\ngold.ap = %i\n", gold.name, gold.ap)
return 0
end
main(#arg, arg)
Now, as for the reverse search which you described, at this point all you should have to do is check the user's input against an Item's name. Here it is in the main function:
local function main(argc, argv)
local gold = Item.new("Gold", 3)
local bag = {}
eprintf("What are you trying to take? ")
local input = getline()
if (input == gold.name) then
table.insert(bag, gold)
eprintf("You took the %s.\n", gold.name)
else
eprintf("Unrecognized item `%s`.\n", input)
end
return 0
end
I hope this helps!

Lua: Desired Results are Received Then Not Without Changing Code

Right now I'm trying to use Lua to receive variables from barcodes sent out from an outside source. When I run this, there is a variable rotation from the local function rot(input) that appears to be "buggy". If I run this code exactly as it is with the print statements below, the rotation will appear and disappear. Please help me understand why this may happen?
Please note: There are two aspects of this code that I'm currently working on. A) Code128 is not properly retrieving the variables. B)My code can definitely be shortened. But I'm new and learning as I go. The main purpose for this thread is to help me understand why code will sometimes display the desired result, then won't the next minute?
Thank you.
Edited: I've updated the code a bit to make it cleaner. Condensed all of my string.match statements into tables with other barcode related fields. Still learning and looking to make it even more cleaner. I love learning this, but am still having the same problem with my local function rot(input) and getting intermittent results. Any help is greatly appreciated!
local function rot(input)
rotTable = {["R"] = "cw", ["I"] = "180", ["B"] = "ccw"}
for k,v in pairs (rotTable) do
if input == k then
rotation = v
else
rotation = ""
end
end
return rotation
end
local function barCode(input)
local bcID = string.match(input,"%^(B%w)")
if bcID == "BY" then
bcID = string.match(input,"%^BY.*%^(B%w)")
end
local bcTable = {
["BC"] = {"code128", 10, string.match(input,"%^BY.*%^BC(%u),(%d*),(%u),%u,%u%^FD(.*)%^FS")},
["B2"] = {"bc2of5i", 20, string.match(input,"%^B2(%u),(%d*),(%u),%u,%u%^FD(.*)%^FS")},
["BE"] = {"ean13", 10, string.match(input,"%^BE(%u),(%d*),(%u),%u%^FD(.*)%^FS")},
["B8"] = {"ean8", 10, string.match(input,"%^B8(%u),(%d*),(%u),%u%^FD(.*)%^FS")},
["B3"] = {"code39", 10, string.match(input,"%^B3(%u),%u,(%d*),(%u),%u%^FD(.*)%^FS")},
["BU"] = {"upc_a", -1, string.match(input,"%^BU(%u),(%d*),(%u),%u%,%u^FD(.*)%^FS")}
}
for k,v in pairs (bcTable) do
if bcID == k then
bcFields = v
bcType, qzone, bcR, bcH, bcHr, bcData = unpack(bcFields)
end
end
hPos = 0
vPos = 0
bcOutput = '<'..bcType..' qzone=\"'..qzone..'\" hbb=\"0\" vbb=\"0\" bbwidth=\"1\" hpos=\"'..hPos..'\" vpos=\"'..vPos..'\" rotation = \"'..rot(bcR)..'\" bgcolor=\"0\" barcolor=\"255\" textcolor=\"255\" barwidth=\"1\" height=\"8\">'..bcData..'</'..bcType..'>'
return bcOutput
end
print(barCode("^BY3^BCN,102,N,N^FDCHF05000042^FS"))
print(barCode("^B2B,110,N,N,N^FD45681382^FS"))
print(barCode("^BUN,183,N,N,N^FD61414199999^FS"))
print(barCode("^B8I,146,N,N^FD212345645121^FS"))
print(barCode("^BEB,183,N,N^FD211234567891^FS"))
I'm not sure what is wrong with your code, if anything, but rot can be written more simply as
local rotTable = {["R"] = "cw", ["I"] = "180", ["B"] = "ccw"}
local function rot(input)
return rotTable[input] or ""
end
In general, you shouldn't need to search Lua tables. For instance, the loop for k,v in pairs (bcTable) do can be replace by indexing as in the code above.

How to setup the correct logic for picking a random item from a list based on item's rarity i.e "rare" "normal"

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

Slplit IPv4 address to minimum and maximum range

Using Lua how do I split a given IP address to get the minimum and maximum range for example:
94.19.21.119
I have a csv like this:
18087936,18153471,"AU"
18153472,18219007,"JP"
18219008,18350079,"IN"
18350080,18874367,"CN"
thats read to 3 tables and the csv is min,max,country code:
IPfrom = {}
IPto = {}
IPCountry = {}
they get populated like this:
IPfrom[18087936] = L
IPto[L] = 18153471
IPCountry[L] = "AU"
with L being the line number of the io.read, what Im then trying to do is get the minimum range so I can without looping check if it exists then if it does that key holds the index of the maximum range and if the ip is within the min/max I get the country code. Probably a different way of doing things but the tables are over 100000 entries so looping is taking some time.
Perhaps something like the following will work for you:
--
-- Converts an IPv4 address into its integer value
--
function iptoint(ip)
local ipint = 0
local iter = string.gmatch(ip, "%d+")
for i = 3, 0, -1 do
local piece = tonumber(iter())
if piece == nil or piece < 0 or piece > 255 then
return nil
end
ipint = bit32.bor(ipint, bit32.lshift(piece, 8 * i))
end
return ipint
end
--
-- Looks up an IPv4 address in a multidimensional table, with the entries:
-- {start_address, end_address, country}
-- and returns the matching country
--
function iptocountry(ip, tbl)
local ipint = iptoint(ip)
if ipint == nil then
return nil
end
for _,v in pairs(tbl) do
if ipint >= v[1] and ipint <= v[2] then
return v[3]
end
end
return nil
end
Example usage:
local countries = {
{16777216, 17367039, "US"},
{1578300000, 1678300000, "CAN"}
-- ... rest of entries loaded from CSV file
}
local ip = "94.19.21.119"
print (iptocountry(ip, countries)) -- prints CAN
A hash table (the basic type in Lua) will give you O(N). An array (a table with no holes with indices from someMinAddr to someMaxAddr) will give you O(1), but use a significant amount of memory. A binary search through a properly sorted structured table could give you O(log N), which for 100000 addresses is probably worth the effort. I imagine you could have a structure like this:
IPfrom = {
{line=L1, addFrom=from1, addrTo=to1, c=country1},
{line=L2, addFrom=from2, addrTo=to2, c=country2},
{line=L3, addFrom=from3, addrTo=to3, c=country3},
{line=L4, addFrom=from4, addrTo=to4, c=country4},
...
}
because I don't see the point of separating the to and country fields from the other info, just means more table lookup. Anyways if you really do want to separate them the following is not affected:
-- init:
create table from CSV file
sort IPFrom on addFrom field
-- as many times as required:
function findIP(addr)
is addr smaller than IPfrom[middle].addrTo3?
if yes, is addr smaller than IPfrom[middle of middle]?
etc
end
This is recursive so if you structure it properly you can use tail calls and not worry about stack overflow (;), something like
function findIPRecurs(addr, ipTbl, indxMin, indxMax)
local middle = (indxMin + indxMax )/2
local midAddr = ipTbl[middle].addrFrom
if addr < midAddr then
return findIPRecurs(addr, ipTbl, indxMin, middle)
else if addr > midAddr then
return findIPRecurs(addr, ipTbl, middle, indxMax)
else -- have entry:
return middle
end
end
function findIP(addr)
return findIPRecurs(addr, ipTbl, 1, #ipTbl)
end
I have not tested this so there might be some fixing up to do but you get the idea. This will use the same memory as O(N) method but for large arrays will be considerably faster; much less memory than O(1) method, and probably acceptably slower.

Lua Array shuffle not working

I was working on a script to randomize the data inside of my array but I get and error
that says
unexpected symbol near "#"
When I go to that line, and I remove the "#" I get
attempt to perform arithmetic on local `n' (a table value)
Here is my shuffle function
function shuffle(array)
local array = array
local n = #array
local j
local random = math.random
for i=n-1, 1, -1 do
j = random(i)
array[j],array[i] = array[i],array[j]
end
return array
end
and here is what I am trying to randomize
shuffle(new_players)
for name,character in pairs(new_players) do
if (character.inside == true and character.death == 0) then
local player = getPlayerByName(name, map_copy)
if (player ~= nil) then
addState(player)
break
end
end
end
Here is my array
new_players= { }
new_players[charName] = { death = 0, inside= true }
Any help? If i am doing something completely wrong?
1) Try change charName from string to a number.
2) For shuffle you can use this code:
function swap(array, index1, index2)
array[index1], array[index2] = array[index2], array[index1]
end
function shuffle(array)
local counter = #array
while counter > 1 do
local index = math.random(counter)
swap(array, index, counter)
counter = counter - 1
end
end
If your Lua version is < 5.1 then there is no # operator. Use table.getn instead:
local n = table.getn(array);
(Update) Note that your function, while it does shuffle the items around, it does not really shuffle all elements. Also since you reduce the range with each iteration, you will almost certainly swap the first 10% of your array around multiple times. Now swapping them multiple times is not bad by itself, but that you are, by comparison, almost never swapping the other elements is.
So one option to solve this would be to always use the same range for your random variable. And I would go even further and select two random indexes to swap:
function shuffle(array)
local n, random, j = table.getn(array), math.random
for i=1, n do
j,k = random(n), random(n)
array[j],array[k] = array[k],array[j]
end
return array
end
The other option would be to select random elements from the source array and put them into a new output array:
local rnd,trem,getn,ins = math.random,table.remove,table.getn,table.insert;
function shuffle(a)
local r = {};
while getn(a) > 0 do
ins(r, trem(a, rnd(getn(a))));
end
return r;
end

Resources