Jump to content

math.random for tables


myonlake

Recommended Posts

  • MTA Team

Hello there,

I was thinking of a random sound fetching from a table with math.random function and decided to try it.

However, instead of playing the songs, it gives me an error about that attachElements, which could be relative to the table stuff, something wrong there?

By the way, this is not the whole script and it wouldn't help much even if I did give you that. It's somewhere here.

I have everything in meta.xml and in the server side.

local soundtable = { "images/mmmp.mp3", "images/cv.mp3", "images/rr.wav", "images/mn.mp3", "images/wwd.mp3" } 
  
function musicpod(source) 
    local x, y, z = getElementPosition(source) 
    local m3d = playSound3D(math.random(#soundtable), x, y, z, false) 
    setSoundVolume(m3d, 0.5) 
    setSoundMaxDistance(m3d, 50) 
    attachElements(m3d, source) 
end 
addEvent("onPodClick", true) 
addEventHandler("onPodClick", getRootElement(), musicpod) 
 
Edited by myonlake
Link to comment

Try

local soundtable = { "images/mmmp.mp3", "images/cv.mp3", "images/rr.wav", "images/mn.mp3", "images/wwd.mp3" } 
  
function musicpod( ) 
    local x, y, z = getElementPosition( source ) 
    local m3d = playSound3D( math.random( 1,#soundtable ), x, y, z, false ) 
    setSoundVolume( m3d, 0.5) 
    setSoundMaxDistance( m3d, 50 ) 
    attachElements( m3d, source ) 
end 
addEvent("onPodClick", true) 
addEventHandler("onPodClick", root, musicpod) 

If it not work please show how you trigger event "onPodClick"

Link to comment
local m3d = playSound3D(math.random(#soundtable), x, y, z, false) 

The error is here. You get the random number, but instead of using it as a table index, you're passing it directly to the function. You need to write soundtable[math.random(#soundtable)] as the first argument.

Link to comment

Yeah my error -_-

This should work:

local soundtable = { "images/mmmp.mp3", "images/cv.mp3", "images/rr.wav", "images/mn.mp3", "images/wwd.mp3" } 
  
function musicpod( ) 
    local x, y, z = getElementPosition( source ) 
    local m3d = playSound3D( soundtable[ math.random( 1,#soundtable ) ], x, y, z, false ) 
    setSoundVolume( m3d, 0.5) 
    setSoundMaxDistance( m3d, 50 ) 
    attachElements( m3d, source ) 
end 
addEvent("onPodClick", true) 
addEventHandler("onPodClick", root, musicpod) 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...