Ad
Log in to vote
0

Problem with for i,v in pairs returning a number?

Asked by
dirk29 0
7 years ago

I have this function towards the top of my script.

function maps() for i,v in ipairs(game.Lighting.Maps:GetChildren()) do wait(1) return i end end

I currently have a group in Lighting called 'Maps'. I have 2 maps in the Map group.

A little way down the script I have this now,

local Num = math.random(1,maps())
wait(3)
message("Welcome to Speed Runner! | V"..ver.." | Game Setting Up...",5)
message("Maps Loaded: "..maps().."",2)
message("Choosing Map",3)

(I have a message function at the top but that's not the problem.)

In the center the "Maps Loaded:" only says one. I can't get it to say two although I have 2 maps in lighting. What I don't understand is why is the function maps() only returning 1 map? Is there a way around this? It's probably an easy fix but for the life of me I cant figure this out.

2 answers

Log in to vote
0
Answered by 7 years ago

You have to create the message first, if you haven't done so already;

local g = Instance.new('Message', Workspace)
g.Text = "Welcome to Speed Runner!"

wait()
g:Destroy()

I'm not sure if this is what you're looking for, but if you just type "Message("Welcome to Speed Runner!"), then message wouldn't be a valid member of game because you have to actually create it.

I'm not sure if you have this somewhere else in the code but.. Hope this helped.

Ad
Log in to vote
0
Answered by
BlueTaslem 18066 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago

Let's first examine your maps function.

function maps()
    for i,v in ipairs(game.Lighting.Maps:GetChildren()) do
        wait(1)
        return i
    end
end

I'm going to change it slightly so that it uses a parameter and selects from a list. We'll call it select:

function select(list)
    for i,v in pairs( list ) do
        -- Ignore the wait -- it's not important since we're returning right away
        return i
    end
end

There's an issue here. return stops execution. That means we'll only do this for the first thing it comes across in the loop.

i is the index in the list, v is the value. Since it's a list, we'll have listofmaps[1] be one map and listofmaps[2] be another map. 1 will be the first value of i, so it will return that.


I'm not exactly sure why you're using maps as a function at all. It seems more like you just need the list of all maps, which would just be

maps = game.Lighting.Maps:GetChildren()
-- You should use ReplicatedStorage / ServerStorage instead

You can get the number of maps using simple #maps (which is the length of the list maps) and you can get the ith map from it simply using maps[i].

Answer this question