Skip to content

Commit

Permalink
Move standard library functions to core
Browse files Browse the repository at this point in the history
  • Loading branch information
desplesda committed Nov 22, 2023
1 parent 164e234 commit 977b8d2
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Added

- Standard library functions (e.g. `random`, `round_places`, `dice`) have been moved to the core Yarn Spinner library.

### Changed

- Updated the schema for .ysls.json files:
Expand Down
77 changes: 77 additions & 0 deletions YarnSpinner/Dialogue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,8 @@ private float GetNodeVisitCount(string nodeName)
// The standard, built-in library of functions and operators.
internal class StandardLibrary : Library
{
private static System.Random Random = new Random();

public StandardLibrary()
{
#region Operators
Expand Down Expand Up @@ -1132,6 +1134,81 @@ public StandardLibrary()
this.RegisterMethods(BuiltinTypes.String);
this.RegisterMethods(BuiltinTypes.Boolean);

#pragma warning disable CA5394 // System.Random is not cryptographically secure

// Register the built-in functions.
this.RegisterFunction("random", delegate ()
{
return Random.NextDouble();
});

this.RegisterFunction("random_range", delegate (float minInclusive, float maxInclusive)
{
var t = Random.NextDouble();
return minInclusive + t * (maxInclusive - minInclusive);
});

this.RegisterFunction("dice", delegate (int sides)
{
return Random.Next(1, sides + 1);
});

#pragma warning restore CA5394

this.RegisterFunction("round", delegate (float num)
{
return (float)Math.Round(num, 0);
});

this.RegisterFunction("round_places", delegate (float num, int places)
{
return (float)Math.Round(num, places);
});

this.RegisterFunction("floor", delegate (float num)
{
return (float)(int)Math.Floor(num);
});

this.RegisterFunction("ceil", delegate (float num)
{
return (float)(int)Math.Ceiling(num);
});

this.RegisterFunction("inc", delegate (float num)
{
if ((num - Math.Truncate(num)) != 0)
{
return Math.Ceiling(num);
}
else
{
return (int)(num + 1);
}
});

this.RegisterFunction("dec", delegate (float num)
{
if ((num - Math.Truncate(num)) != 0)
{
return Math.Floor(num);
}
else
{
return (int)(num - 1);
}
});

this.RegisterFunction("decimal", delegate (float num)
{
return num - Math.Truncate(num);
});

this.RegisterFunction("int", delegate (float num)
{
return Math.Truncate(num);
});

#endregion Operators
}
}
Expand Down

0 comments on commit 977b8d2

Please sign in to comment.