text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
fileFormatVersion: 2
guid: cbf24ddeec4054edc9ad4c8295556878
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
: Any
second:
enabled: 0
settings:
Exclude Android: 1
Exclude CloudRendering: 1
Exclude Editor: 0
Exclude Linux: 0
Exclude Linux64: 0
Exclude LinuxUniversal: 0
Exclude OSXUniversal: 0
Exclude WebGL: 1
Exclude Win: 0
Exclude Win64: 0
Exclude iOS: 1
- first:
Android: Android
second:
enabled: 0
settings:
CPU: ARMv7
- first:
Any:
second:
enabled: 0
settings: {}
- first:
CloudRendering: CloudRendering
second:
enabled: 0
settings: {}
- first:
Editor: Editor
second:
enabled: 1
settings:
CPU: AnyCPU
DefaultValueInitialized: true
OS: AnyOS
- first:
Facebook: Win
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Facebook: Win64
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
Standalone: Linux
second:
enabled: 1
settings:
CPU: x86
- first:
Standalone: Linux64
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: LinuxUniversal
second:
enabled: 1
settings: {}
- first:
Standalone: OSXUniversal
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: Win
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Standalone: Win64
second:
enabled: 1
settings:
CPU: AnyCPU
- first:
Windows Store Apps: WindowsStoreApps
second:
enabled: 0
settings:
CPU: AnyCPU
- first:
iPhone: iOS
second:
enabled: 0
settings:
AddToEmbeddedBinaries: false
CPU: AnyCPU
CompileFlags:
FrameworkDependencies:
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/Grpc.Core.dll.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/Grpc.Core.dll.meta",
"repo_id": "ml-agents",
"token_count": 1061
} | 2,000 |
fileFormatVersion: 2
guid: a961485c3484a4002ac4961a8481f6cc
folderAsset: yes
timeCreated: 1521595360
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/runtimes/win.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Plugins/ProtoBuffer/runtimes/win.meta",
"repo_id": "ml-agents",
"token_count": 82
} | 2,001 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Unity.MLAgents.Actuators
{
/// <summary>
/// ActionSegment{T} is a data structure that allows access to a segment of an underlying array
/// in order to avoid the copying and allocation of sub-arrays. The segment is defined by
/// the offset into the original array, and an length.
/// </summary>
/// <typeparam name="T">The type of object stored in the underlying <see cref="Array"/></typeparam>
public readonly struct ActionSegment<T> : IEnumerable<T>, IEquatable<ActionSegment<T>>
where T : struct
{
/// <summary>
/// The zero-based offset into the original array at which this segment starts.
/// </summary>
public readonly int Offset;
/// <summary>
/// The number of items this segment can access in the underlying array.
/// </summary>
public readonly int Length;
/// <summary>
/// An Empty segment which has an offset of 0, a Length of 0, and it's underlying array
/// is also empty.
/// </summary>
public static ActionSegment<T> Empty = new ActionSegment<T>(System.Array.Empty<T>(), 0, 0);
static void CheckParameters(IReadOnlyCollection<T> actionArray, int offset, int length)
{
#if DEBUG
if (offset + length > actionArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(offset),
$"Arguments offset: {offset} and length: {length} " +
$"are out of bounds of actionArray: {actionArray.Count}.");
}
#endif
}
/// <summary>
/// Construct an <see cref="ActionSegment{T}"/> with just an actionArray. The <see cref="Offset"/> will
/// be set to 0 and the <see cref="Length"/> will be set to `actionArray.Length`.
/// </summary>
/// <param name="actionArray">The action array to use for the this segment.</param>
public ActionSegment(T[] actionArray)
: this(actionArray ?? System.Array.Empty<T>(), 0, actionArray?.Length ?? 0) { }
/// <summary>
/// Construct an <see cref="ActionSegment{T}"/> with an underlying array
/// and offset, and a length.
/// </summary>
/// <param name="actionArray">The underlying array which this segment has a view into</param>
/// <param name="offset">The zero-based offset into the underlying array.</param>
/// <param name="length">The length of the segment.</param>
public ActionSegment(T[] actionArray, int offset, int length)
{
#if DEBUG
CheckParameters(actionArray ?? System.Array.Empty<T>(), offset, length);
#endif
Array = actionArray ?? System.Array.Empty<T>();
Offset = offset;
Length = length;
}
/// <summary>
/// Get the underlying <see cref="Array"/> of this segment.
/// </summary>
public T[] Array { get; }
/// <summary>
/// Allows access to the underlying array using array syntax.
/// </summary>
/// <param name="index">The zero-based index of the segment.</param>
/// <exception cref="IndexOutOfRangeException">Thrown when the index is less than 0 or
/// greater than or equal to <see cref="Length"/></exception>
public T this[int index]
{
get
{
if (index < 0 || index > Length)
{
throw new IndexOutOfRangeException($"Index out of bounds, expected a number between 0 and {Length}");
}
return Array[Offset + index];
}
set
{
if (index < 0 || index > Length)
{
throw new IndexOutOfRangeException($"Index out of bounds, expected a number between 0 and {Length}");
}
Array[Offset + index] = value;
}
}
/// <summary>
/// Sets the segment of the backing array to all zeros.
/// </summary>
public void Clear()
{
System.Array.Clear(Array, Offset, Length);
}
/// <summary>
/// Check if the segment is empty.
/// </summary>
/// <returns>Whether or not the segment is empty.</returns>
public bool IsEmpty()
{
return Array == null || Array.Length == 0;
}
/// <summary>
/// Returns an enumerator that iterates through the ActionSegment.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the ActionSegment.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the ActionSegment.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the ActionSegment.</returns>
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Indicates whether the current ActionSegment is equal to another ActionSegment.
/// </summary>
/// <param name="obj">An ActionSegment to compare with this ActionSegment.</param>
/// <returns>true if the current ActionSegment is equal to the other parameter; otherwise, false.</returns>
public override bool Equals(object obj)
{
if (!(obj is ActionSegment<T>))
{
return false;
}
return Equals((ActionSegment<T>)obj);
}
/// <summary>
/// Indicates whether the current ActionSegment is equal to another ActionSegment.
/// </summary>
/// <param name="other">An ActionSegment to compare with this ActionSegment.</param>
/// <returns>true if the current ActionSegment is equal to the other parameter; otherwise, false.</returns>
public bool Equals(ActionSegment<T> other)
{
return Offset == other.Offset && Length == other.Length && Array.SequenceEqual(other.Array);
}
/// <summary>
/// Computes the hash code of the ActionSegment.
/// </summary>
/// <returns>A hash code for the current ActionSegment.</returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = Offset;
hashCode = (hashCode * 397) ^ Length;
hashCode = (hashCode * 397) ^ (Array != null ? Array.GetHashCode() : 0);
return hashCode;
}
}
/// <summary>
/// A private <see cref="IEnumerator{T}"/> for the <see cref="ActionSegment{T}"/> value type which follows its
/// rules of being a view into an underlying <see cref="Array"/>.
/// </summary>
struct Enumerator : IEnumerator<T>
{
readonly T[] m_Array;
readonly int m_Start;
readonly int m_End; // cache Offset + Count, since it's a little slow
int m_Current;
internal Enumerator(ActionSegment<T> arraySegment)
{
Debug.Assert(arraySegment.Array != null);
Debug.Assert(arraySegment.Offset >= 0);
Debug.Assert(arraySegment.Length >= 0);
Debug.Assert(arraySegment.Offset + arraySegment.Length <= arraySegment.Array.Length);
m_Array = arraySegment.Array;
m_Start = arraySegment.Offset;
m_End = arraySegment.Offset + arraySegment.Length;
m_Current = arraySegment.Offset - 1;
}
public bool MoveNext()
{
if (m_Current < m_End)
{
m_Current++;
return m_Current < m_End;
}
return false;
}
public T Current
{
get
{
if (m_Current < m_Start)
throw new InvalidOperationException("Enumerator not started.");
if (m_Current >= m_End)
throw new InvalidOperationException("Enumerator has reached the end already.");
return m_Array[m_Current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
m_Current = m_Start - 1;
}
public void Dispose()
{
}
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Actuators/ActionSegment.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/ActionSegment.cs",
"repo_id": "ml-agents",
"token_count": 3939
} | 2,002 |
namespace Unity.MLAgents.Actuators
{
/// <summary>
/// Interface for writing a mask to disable discrete actions for agents for the next decision.
/// </summary>
public interface IDiscreteActionMask
{
/// <summary>
/// Set whether or not the action index for the given branch is allowed.
/// </summary>
/// <remarks>
/// By default, all discrete actions are allowed.
/// If isEnabled is false, the agent will not be able to perform the actions passed as argument
/// at the next decision for the specified action branch. The actionIndex corresponds
/// to the action options the agent will be unable to perform.
///
/// See [Agents - Actions] for more information on masking actions.
///
/// [Agents - Actions]: https://github.com/Unity-Technologies/ml-agents/blob/release_21_docs/docs/Learning-Environment-Design-Agents.md#masking-discrete-actions
/// </remarks>
/// <param name="branch">The branch for which the actions will be masked.</param>
/// <param name="actionIndex">Index of the action.</param>
/// <param name="isEnabled">Whether the action is allowed or not.</param>
void SetActionEnabled(int branch, int actionIndex, bool isEnabled);
}
}
| ml-agents/com.unity.ml-agents/Runtime/Actuators/IDiscreteActionMask.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Actuators/IDiscreteActionMask.cs",
"repo_id": "ml-agents",
"token_count": 437
} | 2,003 |
fileFormatVersion: 2
guid: 5ad0bc6b45614bb7929d25dd59d5ac38
timeCreated: 1608168600 | ml-agents/com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Analytics/TrainingAnalytics.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 2,004 |
fileFormatVersion: 2
guid: f95d271af72d4b75aa94d308222f79d8
timeCreated: 1587670989 | ml-agents/com.unity.ml-agents/Runtime/Communicator/UnityRLCapabilities.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Communicator/UnityRLCapabilities.cs.meta",
"repo_id": "ml-agents",
"token_count": 39
} | 2,005 |
namespace Unity.MLAgents
{
internal static class EpisodeIdCounter
{
static int s_Counter;
public static int GetEpisodeId()
{
return s_Counter++;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/EpisodeIdCounter.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/EpisodeIdCounter.cs",
"repo_id": "ml-agents",
"token_count": 96
} | 2,006 |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: mlagents_envs/communicator_objects/command.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Unity.MLAgents.CommunicatorObjects {
/// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/command.proto</summary>
internal static partial class CommandReflection {
#region Descriptor
/// <summary>File descriptor for mlagents_envs/communicator_objects/command.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CommandReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjBtbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL2NvbW1hbmQu",
"cHJvdG8SFGNvbW11bmljYXRvcl9vYmplY3RzKi0KDENvbW1hbmRQcm90bxII",
"CgRTVEVQEAASCQoFUkVTRVQQARIICgRRVUlUEAJCJaoCIlVuaXR5Lk1MQWdl",
"bnRzLkNvbW11bmljYXRvck9iamVjdHNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Unity.MLAgents.CommunicatorObjects.CommandProto), }, null));
}
#endregion
}
#region Enums
internal enum CommandProto {
[pbr::OriginalName("STEP")] Step = 0,
[pbr::OriginalName("RESET")] Reset = 1,
[pbr::OriginalName("QUIT")] Quit = 2,
}
#endregion
}
#endregion Designer generated code
| ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/Command.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/Command.cs",
"repo_id": "ml-agents",
"token_count": 755
} | 2,007 |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: mlagents_envs/communicator_objects/unity_input.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Unity.MLAgents.CommunicatorObjects {
/// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/unity_input.proto</summary>
internal static partial class UnityInputReflection {
#region Descriptor
/// <summary>File descriptor for mlagents_envs/communicator_objects/unity_input.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UnityInputReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjRtbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL3VuaXR5X2lu",
"cHV0LnByb3RvEhRjb21tdW5pY2F0b3Jfb2JqZWN0cxo3bWxhZ2VudHNfZW52",
"cy9jb21tdW5pY2F0b3Jfb2JqZWN0cy91bml0eV9ybF9pbnB1dC5wcm90bxpG",
"bWxhZ2VudHNfZW52cy9jb21tdW5pY2F0b3Jfb2JqZWN0cy91bml0eV9ybF9p",
"bml0aWFsaXphdGlvbl9pbnB1dC5wcm90byKkAQoPVW5pdHlJbnB1dFByb3Rv",
"EjkKCHJsX2lucHV0GAEgASgLMicuY29tbXVuaWNhdG9yX29iamVjdHMuVW5p",
"dHlSTElucHV0UHJvdG8SVgoXcmxfaW5pdGlhbGl6YXRpb25faW5wdXQYAiAB",
"KAsyNS5jb21tdW5pY2F0b3Jfb2JqZWN0cy5Vbml0eVJMSW5pdGlhbGl6YXRp",
"b25JbnB1dFByb3RvQiWqAiJVbml0eS5NTEFnZW50cy5Db21tdW5pY2F0b3JP",
"YmplY3RzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Unity.MLAgents.CommunicatorObjects.UnityRlInputReflection.Descriptor, global::Unity.MLAgents.CommunicatorObjects.UnityRlInitializationInputReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Unity.MLAgents.CommunicatorObjects.UnityInputProto), global::Unity.MLAgents.CommunicatorObjects.UnityInputProto.Parser, new[]{ "RlInput", "RlInitializationInput" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class UnityInputProto : pb::IMessage<UnityInputProto> {
private static readonly pb::MessageParser<UnityInputProto> _parser = new pb::MessageParser<UnityInputProto>(() => new UnityInputProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UnityInputProto> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Unity.MLAgents.CommunicatorObjects.UnityInputReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnityInputProto() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnityInputProto(UnityInputProto other) : this() {
RlInput = other.rlInput_ != null ? other.RlInput.Clone() : null;
RlInitializationInput = other.rlInitializationInput_ != null ? other.RlInitializationInput.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnityInputProto Clone() {
return new UnityInputProto(this);
}
/// <summary>Field number for the "rl_input" field.</summary>
public const int RlInputFieldNumber = 1;
private global::Unity.MLAgents.CommunicatorObjects.UnityRLInputProto rlInput_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Unity.MLAgents.CommunicatorObjects.UnityRLInputProto RlInput {
get { return rlInput_; }
set {
rlInput_ = value;
}
}
/// <summary>Field number for the "rl_initialization_input" field.</summary>
public const int RlInitializationInputFieldNumber = 2;
private global::Unity.MLAgents.CommunicatorObjects.UnityRLInitializationInputProto rlInitializationInput_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Unity.MLAgents.CommunicatorObjects.UnityRLInitializationInputProto RlInitializationInput {
get { return rlInitializationInput_; }
set {
rlInitializationInput_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UnityInputProto);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UnityInputProto other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(RlInput, other.RlInput)) return false;
if (!object.Equals(RlInitializationInput, other.RlInitializationInput)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (rlInput_ != null) hash ^= RlInput.GetHashCode();
if (rlInitializationInput_ != null) hash ^= RlInitializationInput.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (rlInput_ != null) {
output.WriteRawTag(10);
output.WriteMessage(RlInput);
}
if (rlInitializationInput_ != null) {
output.WriteRawTag(18);
output.WriteMessage(RlInitializationInput);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (rlInput_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RlInput);
}
if (rlInitializationInput_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RlInitializationInput);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UnityInputProto other) {
if (other == null) {
return;
}
if (other.rlInput_ != null) {
if (rlInput_ == null) {
rlInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityRLInputProto();
}
RlInput.MergeFrom(other.RlInput);
}
if (other.rlInitializationInput_ != null) {
if (rlInitializationInput_ == null) {
rlInitializationInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityRLInitializationInputProto();
}
RlInitializationInput.MergeFrom(other.RlInitializationInput);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (rlInput_ == null) {
rlInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityRLInputProto();
}
input.ReadMessage(rlInput_);
break;
}
case 18: {
if (rlInitializationInput_ == null) {
rlInitializationInput_ = new global::Unity.MLAgents.CommunicatorObjects.UnityRLInitializationInputProto();
}
input.ReadMessage(rlInitializationInput_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityInput.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityInput.cs",
"repo_id": "ml-agents",
"token_count": 3662
} | 2,008 |
#if UNITY_EDITOR || UNITY_STANDALONE
#define MLA_SUPPORTED_TRAINING_PLATFORM
#endif
#if MLA_SUPPORTED_TRAINING_PLATFORM
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: mlagents_envs/communicator_objects/unity_to_external.proto
// </auto-generated>
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Unity.MLAgents.CommunicatorObjects {
internal static partial class UnityToExternalProto
{
static readonly string __ServiceName = "communicator_objects.UnityToExternalProto";
static readonly grpc::Marshaller<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto> __Marshaller_communicator_objects_UnityMessageProto = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto.Parser.ParseFrom);
static readonly grpc::Method<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto, global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto> __Method_Exchange = new grpc::Method<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto, global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto>(
grpc::MethodType.Unary,
__ServiceName,
"Exchange",
__Marshaller_communicator_objects_UnityMessageProto,
__Marshaller_communicator_objects_UnityMessageProto);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Unity.MLAgents.CommunicatorObjects.UnityToExternalReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of UnityToExternalProto</summary>
public abstract partial class UnityToExternalProtoBase
{
/// <summary>
/// Sends the academy parameters
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto> Exchange(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for UnityToExternalProto</summary>
public partial class UnityToExternalProtoClient : grpc::ClientBase<UnityToExternalProtoClient>
{
/// <summary>Creates a new client for UnityToExternalProto</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public UnityToExternalProtoClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for UnityToExternalProto that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public UnityToExternalProtoClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected UnityToExternalProtoClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected UnityToExternalProtoClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Sends the academy parameters
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto Exchange(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return Exchange(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sends the academy parameters
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto Exchange(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Exchange, null, options, request);
}
/// <summary>
/// Sends the academy parameters
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto> ExchangeAsync(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ExchangeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Sends the academy parameters
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto> ExchangeAsync(global::Unity.MLAgents.CommunicatorObjects.UnityMessageProto request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Exchange, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override UnityToExternalProtoClient NewInstance(ClientBaseConfiguration configuration)
{
return new UnityToExternalProtoClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(UnityToExternalProtoBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Exchange, serviceImpl.Exchange).Build();
}
}
}
#endregion
#endif
| ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityToExternalGrpc.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/UnityToExternalGrpc.cs",
"repo_id": "ml-agents",
"token_count": 2464
} | 2,009 |
fileFormatVersion: 2
guid: 399c5e92395a1484cb2808ac397745e1
timeCreated: 1539197357 | ml-agents/com.unity.ml-agents/Runtime/Inference/SentisModelParamLoader.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/SentisModelParamLoader.cs.meta",
"repo_id": "ml-agents",
"token_count": 39
} | 2,010 |
using System;
namespace Unity.MLAgents.Inference.Utils
{
/// <summary>
/// RandomNormal - A random number generator that produces normally distributed random
/// numbers using the Marsaglia polar method:
/// https://en.wikipedia.org/wiki/Marsaglia_polar_method
/// TODO: worth overriding System.Random instead of aggregating?
/// </summary>
internal class RandomNormal
{
readonly double m_Mean;
readonly double m_Stddev;
readonly Random m_Random;
public RandomNormal(int seed, float mean = 0.0f, float stddev = 1.0f)
{
m_Mean = mean;
m_Stddev = stddev;
m_Random = new Random(seed);
}
// Each iteration produces two numbers. Hold one here for next call
bool m_HasSpare;
double m_SpareUnscaled;
/// <summary>
/// Return the next random double number.
/// </summary>
/// <returns>Next random double number.</returns>
public double NextDouble()
{
if (m_HasSpare)
{
m_HasSpare = false;
return m_SpareUnscaled * m_Stddev + m_Mean;
}
double u, v, s;
do
{
u = m_Random.NextDouble() * 2.0 - 1.0;
v = m_Random.NextDouble() * 2.0 - 1.0;
s = u * u + v * v;
}
while (s >= 1.0 || Math.Abs(s) < double.Epsilon);
s = Math.Sqrt(-2.0 * Math.Log(s) / s);
m_SpareUnscaled = u * s;
m_HasSpare = true;
return v * s * m_Stddev + m_Mean;
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/RandomNormal.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Inference/Utils/RandomNormal.cs",
"repo_id": "ml-agents",
"token_count": 831
} | 2,011 |
using System;
using UnityEngine;
namespace Unity.MLAgents.Integrations.Match3
{
/// <summary>
/// Directions for a Move.
/// </summary>
public enum Direction
{
/// <summary>
/// Move up (increasing row direction).
/// </summary>
Up,
/// <summary>
/// Move down (decreasing row direction).
/// </summary>
Down, // -row direction
/// <summary>
/// Move left (decreasing column direction).
/// </summary>
Left, // -column direction
/// <summary>
/// Move right (increasing column direction).
/// </summary>
Right, // +column direction
}
/// <summary>
/// Struct that encapsulates a swap of adjacent cells.
/// A Move can be constructed from either a starting row, column, and direction,
/// or from a "move index" between 0 and NumPotentialMoves()-1.
/// Moves are enumerated as the internal edges of the game grid.
/// Left/right moves come first. There are (maxCols - 1) * maxRows of these.
/// Up/down moves are next. There are (maxRows - 1) * maxCols of these.
/// </summary>
public struct Move
{
/// <summary>
/// Index of the move, from 0 to NumPotentialMoves-1.
/// </summary>
public int MoveIndex;
/// <summary>
/// Row of the cell that will be moved.
/// </summary>
public int Row;
/// <summary>
/// Column of the cell that will be moved.
/// </summary>
public int Column;
/// <summary>
/// Direction that the cell will be moved.
/// </summary>
public Direction Direction;
/// <summary>
/// Construct a Move from its move index and the board size.
/// This is useful for iterating through all the Moves on a board, or constructing
/// the Move corresponding to an Agent decision.
/// </summary>
/// <param name="moveIndex">Must be between 0 and NumPotentialMoves(maxRows, maxCols).</param>
/// <param name="maxBoardSize"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static Move FromMoveIndex(int moveIndex, BoardSize maxBoardSize)
{
var maxRows = maxBoardSize.Rows;
var maxCols = maxBoardSize.Columns;
if (moveIndex < 0 || moveIndex >= NumPotentialMoves(maxBoardSize))
{
throw new ArgumentOutOfRangeException("moveIndex");
}
Direction dir;
int row, col;
if (moveIndex < (maxCols - 1) * maxRows)
{
dir = Direction.Right;
col = moveIndex % (maxCols - 1);
row = moveIndex / (maxCols - 1);
}
else
{
dir = Direction.Up;
var offset = moveIndex - (maxCols - 1) * maxRows;
col = offset % maxCols;
row = offset / maxCols;
}
return new Move
{
MoveIndex = moveIndex,
Direction = dir,
Row = row,
Column = col
};
}
/// <summary>
/// Increment the Move to the next MoveIndex, and update the Row, Column, and Direction accordingly.
/// </summary>
/// <param name="maxBoardSize"></param>
public void Next(BoardSize maxBoardSize)
{
var maxRows = maxBoardSize.Rows;
var maxCols = maxBoardSize.Columns;
var switchoverIndex = (maxCols - 1) * maxRows;
MoveIndex++;
if (MoveIndex < switchoverIndex)
{
Column++;
if (Column == maxCols - 1)
{
Row++;
Column = 0;
}
}
else if (MoveIndex == switchoverIndex)
{
// switch from moving right to moving up
Row = 0;
Column = 0;
Direction = Direction.Up;
}
else
{
Column++;
if (Column == maxCols)
{
Row++;
Column = 0;
}
}
}
/// <summary>
/// Construct a Move from the row, column, direction, and board size.
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
/// <param name="dir"></param>
/// <param name="maxBoardSize"></param>
/// <returns></returns>
public static Move FromPositionAndDirection(int row, int col, Direction dir, BoardSize maxBoardSize)
{
// Check for out-of-bounds
if (row < 0 || row >= maxBoardSize.Rows)
{
throw new IndexOutOfRangeException($"row was {row}, but must be between 0 and {maxBoardSize.Rows - 1}.");
}
if (col < 0 || col >= maxBoardSize.Columns)
{
throw new IndexOutOfRangeException($"col was {col}, but must be between 0 and {maxBoardSize.Columns - 1}.");
}
// Check moves that would go out of bounds e.g. col == 0 and dir == Left
if (
row == 0 && dir == Direction.Down ||
row == maxBoardSize.Rows - 1 && dir == Direction.Up ||
col == 0 && dir == Direction.Left ||
col == maxBoardSize.Columns - 1 && dir == Direction.Right
)
{
throw new IndexOutOfRangeException($"Cannot move cell at row={row} col={col} in Direction={dir}");
}
// Normalize - only consider Right and Up
if (dir == Direction.Left)
{
dir = Direction.Right;
col = col - 1;
}
else if (dir == Direction.Down)
{
dir = Direction.Up;
row = row - 1;
}
int moveIndex;
if (dir == Direction.Right)
{
moveIndex = col + row * (maxBoardSize.Columns - 1);
}
else
{
var offset = (maxBoardSize.Columns - 1) * maxBoardSize.Rows;
moveIndex = offset + col + row * maxBoardSize.Columns;
}
return new Move
{
Row = row,
Column = col,
Direction = dir,
MoveIndex = moveIndex,
};
}
/// <summary>
/// Check if the move is valid for the given board size.
/// This will be passed the return value from AbstractBoard.GetCurrentBoardSize().
/// </summary>
/// <param name="boardSize"></param>
/// <returns></returns>
public bool InRangeForBoard(BoardSize boardSize)
{
var (otherRow, otherCol) = OtherCell();
// Get the maximum row and column this move would affect.
var maxMoveRow = Mathf.Max(Row, otherRow);
var maxMoveCol = Mathf.Max(Column, otherCol);
return maxMoveRow < boardSize.Rows && maxMoveCol < boardSize.Columns;
}
/// <summary>
/// Get the other row and column that correspond to this move.
/// </summary>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public (int Row, int Column) OtherCell()
{
switch (Direction)
{
case Direction.Up:
return (Row + 1, Column);
case Direction.Down:
return (Row - 1, Column);
case Direction.Left:
return (Row, Column - 1);
case Direction.Right:
return (Row, Column + 1);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Get the opposite direction of this move.
/// </summary>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public Direction OtherDirection()
{
switch (Direction)
{
case Direction.Up:
return Direction.Down;
case Direction.Down:
return Direction.Up;
case Direction.Left:
return Direction.Right;
case Direction.Right:
return Direction.Left;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Return the number of potential moves for a board of the given size.
/// This is equivalent to the number of internal edges in the board.
/// </summary>
/// <param name="maxBoardSize"></param>
/// <returns></returns>
public static int NumPotentialMoves(BoardSize maxBoardSize)
{
return maxBoardSize.Rows * (maxBoardSize.Columns - 1) + (maxBoardSize.Rows - 1) * (maxBoardSize.Columns);
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Move.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Integrations/Match3/Move.cs",
"repo_id": "ml-agents",
"token_count": 4583
} | 2,012 |
using UnityEngine;
namespace Unity.MLAgents.Sensors
{
/// <summary>
/// A SensorComponent that creates a <see cref="BufferSensor"/>.
/// </summary>
[AddComponentMenu("ML Agents/Buffer Sensor", (int)MenuGroup.Sensors)]
public class BufferSensorComponent : SensorComponent
{
/// <summary>
/// Name of the generated <see cref="BufferSensor"/> object.
/// Note that changing this at runtime does not affect how the Agent sorts the sensors.
/// </summary>
public string SensorName
{
get { return m_SensorName; }
set { m_SensorName = value; }
}
[HideInInspector, SerializeField]
private string m_SensorName = "BufferSensor";
/// <summary>
/// This is how many floats each entities will be represented with. This number
/// is fixed and all entities must have the same representation.
/// </summary>
public int ObservableSize
{
get { return m_ObservableSize; }
set { m_ObservableSize = value; }
}
[HideInInspector, SerializeField]
private int m_ObservableSize;
/// <summary>
/// This is the maximum number of entities the `BufferSensor` will be able to
/// collect.
/// </summary>
public int MaxNumObservables
{
get { return m_MaxNumObservables; }
set { m_MaxNumObservables = value; }
}
[HideInInspector, SerializeField]
private int m_MaxNumObservables;
private BufferSensor m_Sensor;
/// <inheritdoc/>
public override ISensor[] CreateSensors()
{
m_Sensor = new BufferSensor(MaxNumObservables, ObservableSize, m_SensorName);
return new ISensor[] { m_Sensor };
}
/// <summary>
/// Appends an observation to the buffer. If the buffer is full (maximum number
/// of observation is reached) the observation will be ignored. the length of
/// the provided observation array must be equal to the observation size of
/// the buffer sensor.
/// </summary>
/// <param name="obs"> The float array observation</param>
public void AppendObservation(float[] obs)
{
m_Sensor.AppendObservation(obs);
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Sensors/BufferSensorComponent.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/BufferSensorComponent.cs",
"repo_id": "ml-agents",
"token_count": 959
} | 2,013 |
using System;
using System.Collections.Generic;
namespace Unity.MLAgents.Sensors
{
/// <summary>
/// The Dimension property flags of the observations
/// </summary>
[Flags]
public enum DimensionProperty
{
/// <summary>
/// No properties specified.
/// </summary>
Unspecified = 0,
/// <summary>
/// No Property of the observation in that dimension. Observation can be processed with
/// fully connected networks.
/// </summary>
None = 1,
/// <summary>
/// Means it is suitable to do a convolution in this dimension.
/// </summary>
TranslationalEquivariance = 2,
/// <summary>
/// Means that there can be a variable number of observations in this dimension.
/// The observations are unordered.
/// </summary>
VariableSize = 4,
}
/// <summary>
/// The ObservationType enum of the Sensor.
/// </summary>
public enum ObservationType
{
/// <summary>
/// Collected observations are generic.
/// </summary>
Default = 0,
/// <summary>
/// Collected observations contain goal information.
/// </summary>
GoalSignal = 1,
}
/// <summary>
/// Sensor interface for generating observations.
/// </summary>
public interface ISensor
{
/// <summary>
/// Returns a description of the observations that will be generated by the sensor.
/// See <see cref="ObservationSpec"/> for more details, and helper methods to create one.
/// </summary>
/// <returns>An object describing the observation.</returns>
ObservationSpec GetObservationSpec();
/// <summary>
/// Write the observation data directly to the <see cref="ObservationWriter"/>.
/// Note that this (and <see cref="GetCompressedObservation"/>) may
/// be called multiple times per agent step, so should not mutate any internal state.
/// </summary>
/// <param name="writer">Where the observations will be written to.</param>
/// <returns>The number of elements written.</returns>
int Write(ObservationWriter writer);
/// <summary>
/// Return a compressed representation of the observation. For small observations,
/// this should generally not be implemented. However, compressing large observations
/// (such as visual results) can significantly improve model training time.
/// </summary>
/// <returns>Compressed observation.</returns>
byte[] GetCompressedObservation();
/// <summary>
/// Update any internal state of the sensor. This is called once per each agent step.
/// </summary>
void Update();
/// <summary>
/// Resets the internal state of the sensor. This is called at the end of an Agent's episode.
/// Most implementations can leave this empty.
/// </summary>
void Reset();
/// <summary>
/// Return information on the compression type being used. If no compression is used, return
/// <see cref="CompressionSpec.Default()"/>.
/// </summary>
/// <returns>An object describing the compression used by the sensor.</returns>
CompressionSpec GetCompressionSpec();
/// <summary>
/// Get the name of the sensor. This is used to ensure deterministic sorting of the sensors
/// on an Agent, so the naming must be consistent across all sensors and agents.
/// </summary>
/// <returns>The name of the sensor.</returns>
string GetName();
}
/// <summary>
/// Helper methods to be shared by all classes that implement <see cref="ISensor"/>.
/// </summary>
public static class SensorExtensions
{
/// <summary>
/// Get the total number of elements in the ISensor's observation (i.e. the product of the
/// shape elements).
/// </summary>
/// <param name="sensor"></param>
/// <returns></returns>
public static int ObservationSize(this ISensor sensor)
{
var obsSpec = sensor.GetObservationSpec();
var count = 1;
for (var i = 0; i < obsSpec.Rank; i++)
{
count *= obsSpec.Shape[i];
}
return count;
}
}
internal static class SensorUtils
{
internal static void SortSensors(List<ISensor> sensors)
{
// Use InvariantCulture to ensure consistent sorting between different culture settings.
sensors.Sort((x, y) => string.Compare(x.GetName(), y.GetName(), StringComparison.InvariantCulture));
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/Sensors/ISensor.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/ISensor.cs",
"repo_id": "ml-agents",
"token_count": 1784
} | 2,014 |
fileFormatVersion: 2
guid: 08ece3d7e9bb94089a9d59c6f269ab0a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/Reflection.meta",
"repo_id": "ml-agents",
"token_count": 72
} | 2,015 |
fileFormatVersion: 2
guid: e3966c9961b343108808d91a4d140a68
timeCreated: 1572300800 | ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/Sensors/VectorSensor.cs.meta",
"repo_id": "ml-agents",
"token_count": 38
} | 2,016 |
using System.Collections.Generic;
using System;
using UnityEngine;
namespace Unity.MLAgents.SideChannels
{
/// <summary>
/// Side channels provide an alternative mechanism of sending/receiving data from Unity
/// to Python that is outside of the traditional machine learning loop. ML-Agents provides
/// some specific implementations of side channels, but users can create their own.
///
/// To create your own, you'll need to create two, new mirrored classes, one in Unity (by
/// extending <see cref="SideChannel"/>) and another in Python by extending a Python class
/// also called SideChannel. Then, within your project, use
/// <see cref="SideChannelManager.RegisterSideChannel"/> and
/// <see cref="SideChannelManager.UnregisterSideChannel"/> to register and unregister your
/// custom side channel.
/// </summary>
public abstract class SideChannel
{
// The list of messages (byte arrays) that need to be sent to Python via the communicator.
// Should only ever be read and cleared by a ICommunicator object.
internal List<byte[]> MessageQueue = new List<byte[]>();
/// <summary>
/// An int identifier for the SideChannel. Ensures that there is only ever one side channel
/// of each type. Ensure the Unity side channels will be linked to their Python equivalent.
/// </summary>
/// <returns> The integer identifier of the SideChannel.</returns>
public Guid ChannelId
{
get;
protected set;
}
internal void ProcessMessage(byte[] msg)
{
try
{
using (var incomingMsg = new IncomingMessage(msg))
{
OnMessageReceived(incomingMsg);
}
}
catch (Exception ex)
{
// Catch all errors in the sidechannel processing, so that a single
// bad SideChannel implementation doesn't take everything down with it.
Debug.LogError($"Error processing SideChannel message: {ex}.\nThe message will be skipped.");
}
}
/// <summary>
/// Is called by the communicator every time a message is received from Python by the SideChannel.
/// Can be called multiple times per simulation step if multiple messages were sent.
/// </summary>
/// <param name="msg">The incoming message.</param>
protected abstract void OnMessageReceived(IncomingMessage msg);
/// <summary>
/// Queues a message to be sent to Python during the next simulation step.
/// </summary>
/// <param name="msg"> The byte array of data to be sent to Python.</param>
protected void QueueMessageToSend(OutgoingMessage msg)
{
MessageQueue.Add(msg.ToByteArray());
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/SideChannels/SideChannel.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/SideChannels/SideChannel.cs",
"repo_id": "ml-agents",
"token_count": 1055
} | 2,017 |
using System;
namespace Unity.MLAgents
{
/// <summary>
/// Contains exceptions specific to ML-Agents.
/// </summary>
[Serializable]
public class UnityAgentsException : Exception
{
/// <summary>
/// When a UnityAgentsException is called, the timeScale is set to 0.
/// The simulation will end since no steps will be taken.
/// </summary>
/// <param name="message">The exception message</param>
public UnityAgentsException(string message) : base(message)
{
}
/// <summary>
/// A constructor is needed for serialization when an exception propagates
/// from a remoting server to the client.
/// </summary>
/// <param name="info">Data for serializing/de-serializing</param>
/// <param name="context">Describes the source and destination of the serialized stream</param>
protected UnityAgentsException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
{
}
}
}
| ml-agents/com.unity.ml-agents/Runtime/UnityAgentsException.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Runtime/UnityAgentsException.cs",
"repo_id": "ml-agents",
"token_count": 407
} | 2,018 |
fileFormatVersion: 2
guid: 18cb6d052fba43a2b7437d87c0d9abad
timeCreated: 1596486604 | ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSegmentTests.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Actuators/ActionSegmentTests.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 2,019 |
fileFormatVersion: 2
guid: d32a102dc1f004c33b05a30190a9d039
timeCreated: 1632841906 | ml-agents/com.unity.ml-agents/Tests/Editor/Areas.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Areas.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 2,020 |
fileFormatVersion: 2
guid: aa4c4ceac5f246a0b341958724ecd752
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ml-agents/com.unity.ml-agents/Tests/Editor/Inference/DiscreteActionOutputApplierTest.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Inference/DiscreteActionOutputApplierTest.cs.meta",
"repo_id": "ml-agents",
"token_count": 94
} | 2,021 |
fileFormatVersion: 2
guid: a6d0404471364cd5b0b86ef72e6fe653
timeCreated: 1601332740 | ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/AbstractBoardTests.cs.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Integrations/Match3/AbstractBoardTests.cs.meta",
"repo_id": "ml-agents",
"token_count": 40
} | 2,022 |
using NUnit.Framework;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Policies;
using UnityEngine;
namespace Unity.MLAgents.Tests.Policies
{
[TestFixture]
public class HeuristicPolicyTest
{
[SetUp]
public void SetUp()
{
if (Academy.IsInitialized)
{
Academy.Instance.Dispose();
}
}
/// <summary>
/// Assert that the action buffers are initialized to zero, and then set them to non-zero values.
/// </summary>
/// <param name="actionsOut"></param>
static void CheckAndSetBuffer(in ActionBuffers actionsOut)
{
var continuousActions = actionsOut.ContinuousActions;
for (var continuousIndex = 0; continuousIndex < continuousActions.Length; continuousIndex++)
{
Assert.AreEqual(continuousActions[continuousIndex], 0.0f);
continuousActions[continuousIndex] = 1.0f;
}
var discreteActions = actionsOut.DiscreteActions;
for (var discreteIndex = 0; discreteIndex < discreteActions.Length; discreteIndex++)
{
Assert.AreEqual(discreteActions[discreteIndex], 0);
discreteActions[discreteIndex] = 1;
}
}
class ActionClearedAgent : Agent
{
public int HeuristicCalls;
public override void Heuristic(in ActionBuffers actionsOut)
{
CheckAndSetBuffer(actionsOut);
HeuristicCalls++;
}
}
class ActionClearedActuator : IActuator
{
public int HeuristicCalls;
public ActionClearedActuator(ActionSpec actionSpec)
{
ActionSpec = actionSpec;
Name = GetType().Name;
}
public void OnActionReceived(ActionBuffers actionBuffers)
{
}
public void WriteDiscreteActionMask(IDiscreteActionMask actionMask)
{
}
public void Heuristic(in ActionBuffers actionBuffersOut)
{
CheckAndSetBuffer(actionBuffersOut);
HeuristicCalls++;
}
public ActionSpec ActionSpec { get; }
public string Name { get; }
public void ResetData()
{
}
}
class ActionClearedActuatorComponent : ActuatorComponent
{
public ActionClearedActuator ActionClearedActuator;
public ActionClearedActuatorComponent()
{
ActionSpec = new ActionSpec(2, new[] { 3, 3 });
}
public override IActuator[] CreateActuators()
{
ActionClearedActuator = new ActionClearedActuator(ActionSpec);
return new IActuator[] { ActionClearedActuator };
}
public override ActionSpec ActionSpec { get; }
}
[Test]
public void TestActionsCleared()
{
var gameObj = new GameObject();
var agent = gameObj.AddComponent<ActionClearedAgent>();
var behaviorParameters = agent.GetComponent<BehaviorParameters>();
behaviorParameters.BrainParameters.ActionSpec = new ActionSpec(1, new[] { 4 });
behaviorParameters.BrainParameters.VectorObservationSize = 0;
behaviorParameters.BehaviorType = BehaviorType.HeuristicOnly;
var actuatorComponent = gameObj.AddComponent<ActionClearedActuatorComponent>();
agent.LazyInitialize();
const int k_NumSteps = 5;
for (var i = 0; i < k_NumSteps; i++)
{
agent.RequestDecision();
Academy.Instance.EnvironmentStep();
}
Assert.AreEqual(agent.HeuristicCalls, k_NumSteps);
Assert.AreEqual(actuatorComponent.ActionClearedActuator.HeuristicCalls, k_NumSteps);
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Editor/Policies/HeuristicPolicyTest.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Policies/HeuristicPolicyTest.cs",
"repo_id": "ml-agents",
"token_count": 1923
} | 2,023 |
fileFormatVersion: 2
guid: 1228f198ceee45a38c7d9ff50425b65d
timeCreated: 1610760867 | ml-agents/com.unity.ml-agents/Tests/Editor/SideChannels.meta/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/SideChannels.meta",
"repo_id": "ml-agents",
"token_count": 39
} | 2,024 |
{
"name": "Unity.ML-Agents.Editor.Tests",
"rootNamespace": "",
"references": [
"Unity.ML-Agents.Editor",
"Unity.ML-Agents",
"Unity.Mathematics",
"Unity.ML-Agents.CommunicatorObjects",
"Unity.ML-Agents.Runtime.Utils.Tests",
"Unity.ML-Agents.Runtime.Sensor.Tests",
"UnityEngine.TestRunner",
"UnityEditor.TestRunner",
"Unity.Sentis"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"System.IO.Abstractions.dll",
"System.IO.Abstractions.TestingHelpers.dll",
"nunit.framework.dll",
"Google.Protobuf_Packed.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS",
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [
{
"name": "com.unity.modules.unityanalytics",
"expression": "1.0.0",
"define": "MLA_UNITY_ANALYTICS_MODULE"
},
{
"name": "com.unity.modules.physics",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS_MODULE"
},
{
"name": "com.unity.modules.physics2d",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS2D_MODULE"
}
],
"noEngineReferences": false
} | ml-agents/com.unity.ml-agents/Tests/Editor/Unity.ML-Agents.Editor.Tests.asmdef/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Editor/Unity.ML-Agents.Editor.Tests.asmdef",
"repo_id": "ml-agents",
"token_count": 746
} | 2,025 |
using NUnit.Framework;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Tests
{
[TestFixture]
public class CompressionSpecTests
{
[Test]
public void TestIsTrivialMapping()
{
Assert.IsTrue(CompressionSpec.Default().IsTrivialMapping());
var spec = new CompressionSpec(SensorCompressionType.PNG, null);
Assert.AreEqual(spec.IsTrivialMapping(), true);
spec = new CompressionSpec(SensorCompressionType.PNG, new[] { 0, 0, 0 });
Assert.AreEqual(spec.IsTrivialMapping(), true);
spec = new CompressionSpec(SensorCompressionType.PNG, new[] { 0, 1, 2, 3, 4 });
Assert.AreEqual(spec.IsTrivialMapping(), true);
spec = new CompressionSpec(SensorCompressionType.PNG, new[] { 1, 2, 3, 4, -1, -1 });
Assert.AreEqual(spec.IsTrivialMapping(), false);
spec = new CompressionSpec(SensorCompressionType.PNG, new[] { 0, 0, 0, 1, 1, 1 });
Assert.AreEqual(spec.IsTrivialMapping(), false);
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/CompressionSpecTests.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/CompressionSpecTests.cs",
"repo_id": "ml-agents",
"token_count": 486
} | 2,026 |
using System;
using NUnit.Framework;
using UnityEngine;
using Unity.MLAgents.Sensors;
namespace Unity.MLAgents.Tests
{
[TestFixture]
public class RenderTextureSensorTests
{
[Test]
public void TestRenderTextureSensor()
{
foreach (var grayscale in new[] { true, false })
{
foreach (SensorCompressionType compression in Enum.GetValues(typeof(SensorCompressionType)))
{
var width = 24;
var height = 16;
var texture = new RenderTexture(width, height, 0);
var sensor = new RenderTextureSensor(texture, grayscale, "TestCameraSensor", compression);
var obsWriter = new ObservationWriter();
var obs = sensor.GetObservationProto(obsWriter);
Assert.AreEqual((int)compression, (int)obs.CompressionType);
var expectedShape = new[] { grayscale ? 1 : 3, height, width };
Assert.AreEqual(expectedShape, obs.Shape);
}
}
}
[Test]
public void TestObservationType()
{
var width = 24;
var height = 16;
var camera = Camera.main;
var sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None);
var spec = sensor.GetObservationSpec();
Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default);
sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None, ObservationType.Default);
spec = sensor.GetObservationSpec();
Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.Default);
sensor = new CameraSensor(camera, width, height, true, "TestCameraSensor", SensorCompressionType.None, ObservationType.GoalSignal);
spec = sensor.GetObservationSpec();
Assert.AreEqual((int)spec.ObservationType, (int)ObservationType.GoalSignal);
}
}
}
| ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/RenderTextureSensorTests.cs/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Sensor/RenderTextureSensorTests.cs",
"repo_id": "ml-agents",
"token_count": 946
} | 2,027 |
{
"name": "Unity.ML-Agents.Runtime.Tests",
"rootNamespace": "",
"references": [
"Unity.ML-Agents",
"Unity.ML-Agents.CommunicatorObjects",
"Unity.ML-Agents.Editor",
"UnityEngine.TestRunner",
"UnityEditor.TestRunner",
"Unity.Sentis"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"System.IO.Abstractions.dll",
"System.IO.Abstractions.TestingHelpers.dll",
"nunit.framework.dll",
"Google.Protobuf_Packed.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS",
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [
{
"name": "com.unity.modules.physics",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS_MODULE"
},
{
"name": "com.unity.modules.physics2d",
"expression": "1.0.0",
"define": "MLA_UNITY_PHYSICS2D_MODULE"
}
],
"noEngineReferences": false
} | ml-agents/com.unity.ml-agents/Tests/Runtime/Unity.ML-Agents.Runtime.Tests.asmdef/0 | {
"file_path": "ml-agents/com.unity.ml-agents/Tests/Runtime/Unity.ML-Agents.Runtime.Tests.asmdef",
"repo_id": "ml-agents",
"token_count": 572
} | 2,028 |
behaviors:
Hallway:
trainer_type: ppo
hyperparameters:
batch_size: 128
buffer_size: 1024
learning_rate: 0.0003
beta: 0.01
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: false
hidden_units: 128
num_layers: 2
vis_encode_type: simple
memory:
sequence_length: 64
memory_size: 256
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
gail:
gamma: 0.99
strength: 0.01
learning_rate: 0.0003
use_actions: false
use_vail: false
demo_path: Project/Assets/ML-Agents/Examples/Hallway/Demos/ExpertHallway.demo
keep_checkpoints: 5
max_steps: 10000000
time_horizon: 64
summary_freq: 10000
| ml-agents/config/imitation/Hallway.yaml/0 | {
"file_path": "ml-agents/config/imitation/Hallway.yaml",
"repo_id": "ml-agents",
"token_count": 415
} | 2,029 |
behaviors:
PushBlock:
trainer_type: ppo
hyperparameters:
batch_size: 128
buffer_size: 2048
learning_rate: 0.0003
beta: 0.01
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: false
hidden_units: 256
num_layers: 2
vis_encode_type: simple
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 2000000
time_horizon: 64
summary_freq: 60000
| ml-agents/config/ppo/PushBlock.yaml/0 | {
"file_path": "ml-agents/config/ppo/PushBlock.yaml",
"repo_id": "ml-agents",
"token_count": 267
} | 2,030 |
behaviors:
Hallway:
trainer_type: sac
hyperparameters:
learning_rate: 0.0003
learning_rate_schedule: constant
batch_size: 512
buffer_size: 200000
buffer_init_steps: 0
tau: 0.005
steps_per_update: 10.0
save_replay_buffer: false
init_entcoef: 0.1
reward_signal_steps_per_update: 10.0
network_settings:
normalize: false
hidden_units: 128
num_layers: 2
vis_encode_type: simple
memory:
sequence_length: 64
memory_size: 128
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 4000000
time_horizon: 64
summary_freq: 10000
| ml-agents/config/sac/Hallway.yaml/0 | {
"file_path": "ml-agents/config/sac/Hallway.yaml",
"repo_id": "ml-agents",
"token_count": 341
} | 2,031 |
# Getting Started Guide
This guide walks through the end-to-end process of opening one of our
[example environments](Learning-Environment-Examples.md) in Unity, training an
Agent in it, and embedding the trained model into the Unity environment. After
reading this tutorial, you should be able to train any of the example
environments. If you are not familiar with the
[Unity Engine](https://unity3d.com/unity), view our
[Background: Unity](Background-Unity.md) page for helpful pointers.
Additionally, if you're not familiar with machine learning, view our
[Background: Machine Learning](Background-Machine-Learning.md) page for a brief
overview and helpful pointers.

For this guide, we'll use the **3D Balance Ball** environment which contains a
number of agent cubes and balls (which are all copies of each other). Each agent
cube tries to keep its ball from falling by rotating either horizontally or
vertically. In this environment, an agent cube is an **Agent** that receives a
reward for every step that it balances the ball. An agent is also penalized with
a negative reward for dropping the ball. The goal of the training process is to
have the agents learn to balance the ball on their head.
Let's get started!
## Installation
If you haven't already, follow the [installation instructions](Installation.md).
Afterwards, open the Unity Project that contains all the example environments:
1. Open the Package Manager Window by navigating to `Window -> Package Manager`
in the menu.
1. Navigate to the ML-Agents Package and click on it.
1. Find the `3D Ball` sample and click `Import`.
1. In the **Project** window, go to the
`Assets/ML-Agents/Examples/3DBall/Scenes` folder and open the `3DBall` scene
file.
## Understanding a Unity Environment
An agent is an autonomous actor that observes and interacts with an
_environment_. In the context of Unity, an environment is a scene containing one
or more Agent objects, and, of course, the other entities that an agent
interacts with.

**Note:** In Unity, the base object of everything in a scene is the
_GameObject_. The GameObject is essentially a container for everything else,
including behaviors, graphics, physics, etc. To see the components that make up
a GameObject, select the GameObject in the Scene window, and open the Inspector
window. The Inspector shows every component on a GameObject.
The first thing you may notice after opening the 3D Balance Ball scene is that
it contains not one, but several agent cubes. Each agent cube in the scene is an
independent agent, but they all share the same Behavior. 3D Balance Ball does
this to speed up training since all twelve agents contribute to training in
parallel.
### Agent
The Agent is the actor that observes and takes actions in the environment. In
the 3D Balance Ball environment, the Agent components are placed on the twelve
"Agent" GameObjects. The base Agent object has a few properties that affect its
behavior:
- **Behavior Parameters** — Every Agent must have a Behavior. The Behavior
determines how an Agent makes decisions.
- **Max Step** — Defines how many simulation steps can occur before the Agent's
episode ends. In 3D Balance Ball, an Agent restarts after 5000 steps.
#### Behavior Parameters : Vector Observation Space
Before making a decision, an agent collects its observation about its state in
the world. The vector observation is a vector of floating point numbers which
contain relevant information for the agent to make decisions.
The Behavior Parameters of the 3D Balance Ball example uses a `Space Size` of 8.
This means that the feature vector containing the Agent's observations contains
eight elements: the `x` and `z` components of the agent cube's rotation and the
`x`, `y`, and `z` components of the ball's relative position and velocity.
#### Behavior Parameters : Actions
An Agent is given instructions in the form of actions.
ML-Agents Toolkit classifies actions into two types: continuous and discrete.
The 3D Balance Ball example is programmed to use continuous actions, which
are a vector of floating-point numbers that can vary continuously. More specifically,
it uses a `Space Size` of 2 to control the amount of `x` and `z` rotations to apply to
itself to keep the ball balanced on its head.
## Running a pre-trained model
We include pre-trained models for our agents (`.onnx` files) and we use the
[Sentis](Sentis.md) to run these models inside
Unity. In this section, we will use the pre-trained model for the 3D Ball
example.
1. In the **Project** window, go to the
`Assets/ML-Agents/Examples/3DBall/Prefabs` folder. Expand `3DBall` and click
on the `Agent` prefab. You should see the `Agent` prefab in the **Inspector**
window.
**Note**: The platforms in the `3DBall` scene were created using the `3DBall`
prefab. Instead of updating all 12 platforms individually, you can update the
`3DBall` prefab instead.

1. In the **Project** window, drag the **3DBall** Model located in
`Assets/ML-Agents/Examples/3DBall/TFModels` into the `Model` property under
`Behavior Parameters (Script)` component in the Agent GameObject
**Inspector** window.

1. You should notice that each `Agent` under each `3DBall` in the **Hierarchy**
windows now contains **3DBall** as `Model` on the `Behavior Parameters`.
**Note** : You can modify multiple game objects in a scene by selecting them
all at once using the search bar in the Scene Hierarchy.
1. Set the **Inference Device** to use for this model as `CPU`.
1. Click the **Play** button in the Unity Editor and you will see the platforms
balance the balls using the pre-trained model.
## Training a new model with Reinforcement Learning
While we provide pre-trained models for the agents in this environment, any
environment you make yourself will require training agents from scratch to
generate a new model file. In this section we will demonstrate how to use the
reinforcement learning algorithms that are part of the ML-Agents Python package
to accomplish this. We have provided a convenient command `mlagents-learn` which
accepts arguments used to configure both training and inference phases.
### Training the environment
1. Open a command or terminal window.
1. Navigate to the folder where you cloned the `ml-agents` repository. **Note**:
If you followed the default [installation](Installation.md), then you should
be able to run `mlagents-learn` from any directory.
1. Run `mlagents-learn config/ppo/3DBall.yaml --run-id=first3DBallRun`.
- `config/ppo/3DBall.yaml` is the path to a default training
configuration file that we provide. The `config/ppo` folder includes training configuration
files for all our example environments, including 3DBall.
- `run-id` is a unique name for this training session.
1. When the message _"Start training by pressing the Play button in the Unity
Editor"_ is displayed on the screen, you can press the **Play** button in
Unity to start training in the Editor.
If `mlagents-learn` runs correctly and starts training, you should see something
like this:
```console
INFO:mlagents_envs:
'Ball3DAcademy' started successfully!
Unity Academy name: Ball3DAcademy
INFO:mlagents_envs:Connected new brain:
Unity brain name: 3DBallLearning
Number of Visual Observations (per agent): 0
Vector Observation space size (per agent): 8
Number of stacked Vector Observation: 1
INFO:mlagents_envs:Hyperparameters for the PPO Trainer of brain 3DBallLearning:
batch_size: 64
beta: 0.001
buffer_size: 12000
epsilon: 0.2
gamma: 0.995
hidden_units: 128
lambd: 0.99
learning_rate: 0.0003
max_steps: 5.0e4
normalize: True
num_epoch: 3
num_layers: 2
time_horizon: 1000
sequence_length: 64
summary_freq: 1000
use_recurrent: False
memory_size: 256
use_curiosity: False
curiosity_strength: 0.01
curiosity_enc_size: 128
output_path: ./results/first3DBallRun/3DBallLearning
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 1000. Mean Reward: 1.242. Std of Reward: 0.746. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 2000. Mean Reward: 1.319. Std of Reward: 0.693. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 3000. Mean Reward: 1.804. Std of Reward: 1.056. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 4000. Mean Reward: 2.151. Std of Reward: 1.432. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 5000. Mean Reward: 3.175. Std of Reward: 2.250. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 6000. Mean Reward: 4.898. Std of Reward: 4.019. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 7000. Mean Reward: 6.716. Std of Reward: 5.125. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 8000. Mean Reward: 12.124. Std of Reward: 11.929. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 9000. Mean Reward: 18.151. Std of Reward: 16.871. Training.
INFO:mlagents.trainers: first3DBallRun: 3DBallLearning: Step: 10000. Mean Reward: 27.284. Std of Reward: 28.667. Training.
```
Note how the `Mean Reward` value printed to the screen increases as training
progresses. This is a positive sign that training is succeeding.
**Note**: You can train using an executable rather than the Editor. To do so,
follow the instructions in
[Using an Executable](Learning-Environment-Executable.md).
### Observing Training Progress
Once you start training using `mlagents-learn` in the way described in the
previous section, the `ml-agents` directory will contain a `results`
directory. In order to observe the training process in more detail, you can use
TensorBoard. From the command line run:
```sh
tensorboard --logdir results
```
Then navigate to `localhost:6006` in your browser to view the TensorBoard
summary statistics as shown below. For the purposes of this section, the most
important statistic is `Environment/Cumulative Reward` which should increase
throughout training, eventually converging close to `100` which is the maximum
reward the agent can accumulate.

## Embedding the model into the Unity Environment
Once the training process completes, and the training process saves the model
(denoted by the `Saved Model` message) you can add it to the Unity project and
use it with compatible Agents (the Agents that generated the model). **Note:**
Do not just close the Unity Window once the `Saved Model` message appears.
Either wait for the training process to close the window or press `Ctrl+C` at
the command-line prompt. If you close the window manually, the `.onnx` file
containing the trained model is not exported into the ml-agents folder.
If you've quit the training early using `Ctrl+C` and want to resume training,
run the same command again, appending the `--resume` flag:
```sh
mlagents-learn config/ppo/3DBall.yaml --run-id=first3DBallRun --resume
```
Your trained model will be at `results/<run-identifier>/<behavior_name>.onnx` where
`<behavior_name>` is the name of the `Behavior Name` of the agents corresponding
to the model. This file corresponds to your model's latest checkpoint. You can
now embed this trained model into your Agents by following the steps below,
which is similar to the steps described [above](#running-a-pre-trained-model).
1. Move your model file into
`Project/Assets/ML-Agents/Examples/3DBall/TFModels/`.
1. Open the Unity Editor, and select the **3DBall** scene as described above.
1. Select the **3DBall** prefab Agent object.
1. Drag the `<behavior_name>.onnx` file from the Project window of the Editor to
the **Model** placeholder in the **Ball3DAgent** inspector window.
1. Press the **Play** button at the top of the Editor.
## Next Steps
- For more information on the ML-Agents Toolkit, in addition to helpful
background, check out the [ML-Agents Toolkit Overview](ML-Agents-Overview.md)
page.
- For a "Hello World" introduction to creating your own Learning Environment,
check out the
[Making a New Learning Environment](Learning-Environment-Create-New.md) page.
- For an overview on the more complex example environments that are provided in
this toolkit, check out the
[Example Environments](Learning-Environment-Examples.md) page.
- For more information on the various training options available, check out the
[Training ML-Agents](Training-ML-Agents.md) page.
| ml-agents/docs/Getting-Started.md/0 | {
"file_path": "ml-agents/docs/Getting-Started.md",
"repo_id": "ml-agents",
"token_count": 3776
} | 2,032 |
{!../ml-agents/README.md!}
| ml-agents/docs/ML-Agents-README.md/0 | {
"file_path": "ml-agents/docs/ML-Agents-README.md",
"repo_id": "ml-agents",
"token_count": 14
} | 2,033 |
<!-- HTML footer for doxygen 1.8.14-->
<!-- start footer part -->
<!--BEGIN GENERATE_TREEVIEW-->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
$navpath
</ul>
</div>
<!--END GENERATE_TREEVIEW-->
<!--BEGIN !GENERATE_TREEVIEW-->
<hr class="footer"/>
<!--END !GENERATE_TREEVIEW-->
</body>
</html>
| ml-agents/docs/doxygen/footer.html/0 | {
"file_path": "ml-agents/docs/doxygen/footer.html",
"repo_id": "ml-agents",
"token_count": 137
} | 2,034 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mlagents_envs/communicator_objects/agent_action.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='mlagents_envs/communicator_objects/agent_action.proto',
package='communicator_objects',
syntax='proto3',
serialized_pb=_b('\n5mlagents_envs/communicator_objects/agent_action.proto\x12\x14\x63ommunicator_objects\"\x8c\x01\n\x10\x41gentActionProto\x12!\n\x19vector_actions_deprecated\x18\x01 \x03(\x02\x12\r\n\x05value\x18\x04 \x01(\x02\x12\x1a\n\x12\x63ontinuous_actions\x18\x06 \x03(\x02\x12\x18\n\x10\x64iscrete_actions\x18\x07 \x03(\x05J\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04J\x04\x08\x05\x10\x06\x42%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3')
)
_AGENTACTIONPROTO = _descriptor.Descriptor(
name='AgentActionProto',
full_name='communicator_objects.AgentActionProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='vector_actions_deprecated', full_name='communicator_objects.AgentActionProto.vector_actions_deprecated', index=0,
number=1, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='value', full_name='communicator_objects.AgentActionProto.value', index=1,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='continuous_actions', full_name='communicator_objects.AgentActionProto.continuous_actions', index=2,
number=6, type=2, cpp_type=6, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='discrete_actions', full_name='communicator_objects.AgentActionProto.discrete_actions', index=3,
number=7, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=80,
serialized_end=220,
)
DESCRIPTOR.message_types_by_name['AgentActionProto'] = _AGENTACTIONPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AgentActionProto = _reflection.GeneratedProtocolMessageType('AgentActionProto', (_message.Message,), dict(
DESCRIPTOR = _AGENTACTIONPROTO,
__module__ = 'mlagents_envs.communicator_objects.agent_action_pb2'
# @@protoc_insertion_point(class_scope:communicator_objects.AgentActionProto)
))
_sym_db.RegisterMessage(AgentActionProto)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects'))
# @@protoc_insertion_point(module_scope)
| ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/agent_action_pb2.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/agent_action_pb2.py",
"repo_id": "ml-agents",
"token_count": 1479
} | 2,035 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mlagents_envs/communicator_objects/engine_configuration.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='mlagents_envs/communicator_objects/engine_configuration.proto',
package='communicator_objects',
syntax='proto3',
serialized_pb=_b('\n=mlagents_envs/communicator_objects/engine_configuration.proto\x12\x14\x63ommunicator_objects\"\x95\x01\n\x18\x45ngineConfigurationProto\x12\r\n\x05width\x18\x01 \x01(\x05\x12\x0e\n\x06height\x18\x02 \x01(\x05\x12\x15\n\rquality_level\x18\x03 \x01(\x05\x12\x12\n\ntime_scale\x18\x04 \x01(\x02\x12\x19\n\x11target_frame_rate\x18\x05 \x01(\x05\x12\x14\n\x0cshow_monitor\x18\x06 \x01(\x08\x42%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3')
)
_ENGINECONFIGURATIONPROTO = _descriptor.Descriptor(
name='EngineConfigurationProto',
full_name='communicator_objects.EngineConfigurationProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='width', full_name='communicator_objects.EngineConfigurationProto.width', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='height', full_name='communicator_objects.EngineConfigurationProto.height', index=1,
number=2, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='quality_level', full_name='communicator_objects.EngineConfigurationProto.quality_level', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='time_scale', full_name='communicator_objects.EngineConfigurationProto.time_scale', index=3,
number=4, type=2, cpp_type=6, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='target_frame_rate', full_name='communicator_objects.EngineConfigurationProto.target_frame_rate', index=4,
number=5, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='show_monitor', full_name='communicator_objects.EngineConfigurationProto.show_monitor', index=5,
number=6, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=88,
serialized_end=237,
)
DESCRIPTOR.message_types_by_name['EngineConfigurationProto'] = _ENGINECONFIGURATIONPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
EngineConfigurationProto = _reflection.GeneratedProtocolMessageType('EngineConfigurationProto', (_message.Message,), dict(
DESCRIPTOR = _ENGINECONFIGURATIONPROTO,
__module__ = 'mlagents_envs.communicator_objects.engine_configuration_pb2'
# @@protoc_insertion_point(class_scope:communicator_objects.EngineConfigurationProto)
))
_sym_db.RegisterMessage(EngineConfigurationProto)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects'))
# @@protoc_insertion_point(module_scope)
| ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/engine_configuration_pb2.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/engine_configuration_pb2.py",
"repo_id": "ml-agents",
"token_count": 1785
} | 2,036 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mlagents_envs/communicator_objects/unity_rl_initialization_input.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from mlagents_envs.communicator_objects import capabilities_pb2 as mlagents__envs_dot_communicator__objects_dot_capabilities__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='mlagents_envs/communicator_objects/unity_rl_initialization_input.proto',
package='communicator_objects',
syntax='proto3',
serialized_pb=_b('\nFmlagents_envs/communicator_objects/unity_rl_initialization_input.proto\x12\x14\x63ommunicator_objects\x1a\x35mlagents_envs/communicator_objects/capabilities.proto\"\xc0\x01\n\x1fUnityRLInitializationInputProto\x12\x0c\n\x04seed\x18\x01 \x01(\x05\x12\x1d\n\x15\x63ommunication_version\x18\x02 \x01(\t\x12\x17\n\x0fpackage_version\x18\x03 \x01(\t\x12\x44\n\x0c\x63\x61pabilities\x18\x04 \x01(\x0b\x32..communicator_objects.UnityRLCapabilitiesProto\x12\x11\n\tnum_areas\x18\x05 \x01(\x05\x42%\xaa\x02\"Unity.MLAgents.CommunicatorObjectsb\x06proto3')
,
dependencies=[mlagents__envs_dot_communicator__objects_dot_capabilities__pb2.DESCRIPTOR,])
_UNITYRLINITIALIZATIONINPUTPROTO = _descriptor.Descriptor(
name='UnityRLInitializationInputProto',
full_name='communicator_objects.UnityRLInitializationInputProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='seed', full_name='communicator_objects.UnityRLInitializationInputProto.seed', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='communication_version', full_name='communicator_objects.UnityRLInitializationInputProto.communication_version', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='package_version', full_name='communicator_objects.UnityRLInitializationInputProto.package_version', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='capabilities', full_name='communicator_objects.UnityRLInitializationInputProto.capabilities', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='num_areas', full_name='communicator_objects.UnityRLInitializationInputProto.num_areas', index=4,
number=5, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=152,
serialized_end=344,
)
_UNITYRLINITIALIZATIONINPUTPROTO.fields_by_name['capabilities'].message_type = mlagents__envs_dot_communicator__objects_dot_capabilities__pb2._UNITYRLCAPABILITIESPROTO
DESCRIPTOR.message_types_by_name['UnityRLInitializationInputProto'] = _UNITYRLINITIALIZATIONINPUTPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
UnityRLInitializationInputProto = _reflection.GeneratedProtocolMessageType('UnityRLInitializationInputProto', (_message.Message,), dict(
DESCRIPTOR = _UNITYRLINITIALIZATIONINPUTPROTO,
__module__ = 'mlagents_envs.communicator_objects.unity_rl_initialization_input_pb2'
# @@protoc_insertion_point(class_scope:communicator_objects.UnityRLInitializationInputProto)
))
_sym_db.RegisterMessage(UnityRLInitializationInputProto)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\252\002\"Unity.MLAgents.CommunicatorObjects'))
# @@protoc_insertion_point(module_scope)
| ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_input_pb2.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/communicator_objects/unity_rl_initialization_input_pb2.py",
"repo_id": "ml-agents",
"token_count": 1865
} | 2,037 |
from typing import Any, Optional
from gym import error
from mlagents_envs.base_env import BaseEnv
from pettingzoo import AECEnv
from mlagents_envs.envs.unity_pettingzoo_base_env import UnityPettingzooBaseEnv
class UnityAECEnv(UnityPettingzooBaseEnv, AECEnv):
"""
Unity AEC (PettingZoo) environment wrapper.
"""
def __init__(self, env: BaseEnv, seed: Optional[int] = None):
"""
Initializes a Unity AEC environment wrapper.
:param env: The UnityEnvironment that is being wrapped.
:param seed: The seed for the action spaces of the agents.
"""
super().__init__(env, seed)
def step(self, action: Any) -> None:
"""
Sets the action of the active agent and get the observation, reward, done
and info of the next agent.
:param action: The action for the active agent
"""
self._assert_loaded()
if len(self._live_agents) <= 0:
raise error.Error(
"You must reset the environment before you can perform a step"
)
# Process action
current_agent = self._agents[self._agent_index]
self._process_action(current_agent, action)
self._agent_index += 1
# Reset reward
for k in self._rewards.keys():
self._rewards[k] = 0
if self._agent_index >= len(self._agents) and self.num_agents > 0:
# The index is too high, time to set the action for the agents we have
self._step()
self._live_agents.sort() # unnecessary, only for passing API test
def observe(self, agent_id):
"""
Returns the observation an agent currently can make. `last()` calls this function.
"""
return (
self._observations[agent_id],
self._cumm_rewards[agent_id],
self._dones[agent_id],
self._infos[agent_id],
)
def last(self, observe=True):
"""
returns observation, cumulative reward, done, info for the current agent (specified by self.agent_selection)
"""
obs, reward, done, info = self.observe(self._agents[self._agent_index])
return obs if observe else None, reward, done, info
@property
def agent_selection(self):
if not self._live_agents:
# If we had an agent finish then return that agent even though it isn't alive.
return self._agents[0]
return self._agents[self._agent_index]
| ml-agents/ml-agents-envs/mlagents_envs/envs/unity_aec_env.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/envs/unity_aec_env.py",
"repo_id": "ml-agents",
"token_count": 1021
} | 2,038 |
from mlagents_envs.side_channel import SideChannel, OutgoingMessage, IncomingMessage
from mlagents_envs.exception import (
UnityCommunicationException,
UnitySideChannelException,
)
import uuid
from typing import NamedTuple, Optional
from enum import IntEnum
class EngineConfig(NamedTuple):
width: Optional[int]
height: Optional[int]
quality_level: Optional[int]
time_scale: Optional[float]
target_frame_rate: Optional[int]
capture_frame_rate: Optional[int]
@staticmethod
def default_config():
return EngineConfig(80, 80, 1, 20.0, -1, 60)
class EngineConfigurationChannel(SideChannel):
"""
This is the SideChannel for engine configuration exchange. The data in the
engine configuration is as follows :
- int width;
- int height;
- int qualityLevel;
- float timeScale;
- int targetFrameRate;
- int captureFrameRate;
"""
class ConfigurationType(IntEnum):
SCREEN_RESOLUTION = 0
QUALITY_LEVEL = 1
TIME_SCALE = 2
TARGET_FRAME_RATE = 3
CAPTURE_FRAME_RATE = 4
def __init__(self) -> None:
super().__init__(uuid.UUID("e951342c-4f7e-11ea-b238-784f4387d1f7"))
def on_message_received(self, msg: IncomingMessage) -> None:
"""
Is called by the environment to the side channel. Can be called
multiple times per step if multiple messages are meant for that
SideChannel.
Note that Python should never receive an engine configuration from
Unity
"""
raise UnityCommunicationException(
"The EngineConfigurationChannel received a message from Unity, "
+ "this should not have happened."
)
def set_configuration_parameters(
self,
width: Optional[int] = None,
height: Optional[int] = None,
quality_level: Optional[int] = None,
time_scale: Optional[float] = None,
target_frame_rate: Optional[int] = None,
capture_frame_rate: Optional[int] = None,
) -> None:
"""
Sets the engine configuration. Takes as input the configurations of the
engine.
:param width: Defines the width of the display. (Must be set alongside height)
:param height: Defines the height of the display. (Must be set alongside width)
:param quality_level: Defines the quality level of the simulation.
:param time_scale: Defines the multiplier for the deltatime in the
simulation. If set to a higher value, time will pass faster in the
simulation but the physics might break.
:param target_frame_rate: Instructs simulation to try to render at a
specified frame rate.
:param capture_frame_rate: Instructs the simulation to consider time between
updates to always be constant, regardless of the actual frame rate.
"""
if (width is None and height is not None) or (
width is not None and height is None
):
raise UnitySideChannelException(
"You cannot set the width/height of the screen resolution without also setting the height/width"
)
if width is not None and height is not None:
screen_msg = OutgoingMessage()
screen_msg.write_int32(self.ConfigurationType.SCREEN_RESOLUTION)
screen_msg.write_int32(width)
screen_msg.write_int32(height)
super().queue_message_to_send(screen_msg)
if quality_level is not None:
quality_level_msg = OutgoingMessage()
quality_level_msg.write_int32(self.ConfigurationType.QUALITY_LEVEL)
quality_level_msg.write_int32(quality_level)
super().queue_message_to_send(quality_level_msg)
if time_scale is not None:
time_scale_msg = OutgoingMessage()
time_scale_msg.write_int32(self.ConfigurationType.TIME_SCALE)
time_scale_msg.write_float32(time_scale)
super().queue_message_to_send(time_scale_msg)
if target_frame_rate is not None:
target_frame_rate_msg = OutgoingMessage()
target_frame_rate_msg.write_int32(self.ConfigurationType.TARGET_FRAME_RATE)
target_frame_rate_msg.write_int32(target_frame_rate)
super().queue_message_to_send(target_frame_rate_msg)
if capture_frame_rate is not None:
capture_frame_rate_msg = OutgoingMessage()
capture_frame_rate_msg.write_int32(
self.ConfigurationType.CAPTURE_FRAME_RATE
)
capture_frame_rate_msg.write_int32(capture_frame_rate)
super().queue_message_to_send(capture_frame_rate_msg)
def set_configuration(self, config: EngineConfig) -> None:
"""
Sets the engine configuration. Takes as input an EngineConfig.
"""
self.set_configuration_parameters(**config._asdict())
| ml-agents/ml-agents-envs/mlagents_envs/side_channel/engine_configuration_channel.py/0 | {
"file_path": "ml-agents/ml-agents-envs/mlagents_envs/side_channel/engine_configuration_channel.py",
"repo_id": "ml-agents",
"token_count": 1978
} | 2,039 |
from unittest import mock
import pytest
import numpy as np
from gym import spaces
from mlagents_envs.envs.unity_gym_env import UnityToGymWrapper
from mlagents_envs.base_env import (
BehaviorSpec,
ActionSpec,
DecisionSteps,
TerminalSteps,
BehaviorMapping,
)
from dummy_config import create_observation_specs_with_shapes
def test_gym_wrapper():
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec()
mock_decision_step, mock_terminal_step = create_mock_vector_steps(mock_spec)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env)
assert isinstance(env.reset(), np.ndarray)
actions = env.action_space.sample()
assert actions.shape[0] == 2
obs, rew, done, info = env.step(actions)
assert env.observation_space.contains(obs)
assert isinstance(obs, np.ndarray)
assert isinstance(rew, float)
assert isinstance(done, (bool, np.bool_))
assert isinstance(info, dict)
def test_branched_flatten():
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec(
vector_action_space_type="discrete", vector_action_space_size=[2, 2, 3]
)
mock_decision_step, mock_terminal_step = create_mock_vector_steps(
mock_spec, num_agents=1
)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env, flatten_branched=True)
assert isinstance(env.action_space, spaces.Discrete)
assert env.action_space.n == 12
assert env._flattener.lookup_action(0) == [0, 0, 0]
assert env._flattener.lookup_action(11) == [1, 1, 2]
# Check that False produces a MultiDiscrete
env = UnityToGymWrapper(mock_env, flatten_branched=False)
assert isinstance(env.action_space, spaces.MultiDiscrete)
def test_action_space():
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec(
vector_action_space_type="discrete", vector_action_space_size=[5]
)
mock_decision_step, mock_terminal_step = create_mock_vector_steps(
mock_spec, num_agents=1
)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env, flatten_branched=True)
assert isinstance(env.action_space, spaces.Discrete)
assert env.action_space.n == 5
env = UnityToGymWrapper(mock_env, flatten_branched=False)
assert isinstance(env.action_space, spaces.Discrete)
assert env.action_space.n == 5
def test_action_space_seed():
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec()
mock_decision_step, mock_terminal_step = create_mock_vector_steps(mock_spec)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
actions = []
for _ in range(0, 2):
env = UnityToGymWrapper(mock_env, action_space_seed=1337)
env.reset()
actions.append(env.action_space.sample())
assert (actions[0] == actions[1]).all()
@pytest.mark.parametrize("use_uint8", [True, False], ids=["float", "uint8"])
def test_gym_wrapper_visual(use_uint8):
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec(
number_visual_observations=1, vector_observation_space_size=0
)
mock_decision_step, mock_terminal_step = create_mock_vector_steps(
mock_spec, number_visual_observations=1
)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env, uint8_visual=use_uint8)
assert isinstance(env.observation_space, spaces.Box)
assert isinstance(env.reset(), np.ndarray)
actions = env.action_space.sample()
assert actions.shape[0] == 2
obs, rew, done, info = env.step(actions)
assert env.observation_space.contains(obs)
assert isinstance(obs, np.ndarray)
assert isinstance(rew, float)
assert isinstance(done, (bool, np.bool_))
assert isinstance(info, dict)
@pytest.mark.parametrize("use_uint8", [True, False], ids=["float", "uint8"])
def test_gym_wrapper_single_visual_and_vector(use_uint8):
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec(
number_visual_observations=1,
vector_observation_space_size=3,
vector_action_space_size=[2],
)
mock_decision_step, mock_terminal_step = create_mock_vector_steps(
mock_spec, number_visual_observations=1
)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env, uint8_visual=use_uint8, allow_multiple_obs=True)
assert isinstance(env.observation_space, spaces.Tuple)
assert len(env.observation_space) == 2
reset_obs = env.reset()
assert isinstance(reset_obs, list)
assert len(reset_obs) == 2
assert all(isinstance(ob, np.ndarray) for ob in reset_obs)
assert reset_obs[-1].shape == (3,)
assert len(reset_obs[0].shape) == 3
actions = env.action_space.sample()
assert actions.shape == (2,)
obs, rew, done, info = env.step(actions)
assert isinstance(obs, list)
assert len(obs) == 2
assert all(isinstance(ob, np.ndarray) for ob in obs)
assert reset_obs[-1].shape == (3,)
assert isinstance(rew, float)
assert isinstance(done, (bool, np.bool_))
assert isinstance(info, dict)
# check behavior for allow_multiple_obs = False
env = UnityToGymWrapper(mock_env, uint8_visual=use_uint8, allow_multiple_obs=False)
assert isinstance(env.observation_space, spaces.Box)
reset_obs = env.reset()
assert isinstance(reset_obs, np.ndarray)
assert len(reset_obs.shape) == 3
actions = env.action_space.sample()
assert actions.shape == (2,)
obs, rew, done, info = env.step(actions)
assert isinstance(obs, np.ndarray)
@pytest.mark.parametrize("use_uint8", [True, False], ids=["float", "uint8"])
def test_gym_wrapper_multi_visual_and_vector(use_uint8):
mock_env = mock.MagicMock()
mock_spec = create_mock_group_spec(
number_visual_observations=2,
vector_observation_space_size=3,
vector_action_space_size=[2],
)
mock_decision_step, mock_terminal_step = create_mock_vector_steps(
mock_spec, number_visual_observations=2
)
setup_mock_unityenvironment(
mock_env, mock_spec, mock_decision_step, mock_terminal_step
)
env = UnityToGymWrapper(mock_env, uint8_visual=use_uint8, allow_multiple_obs=True)
assert isinstance(env.observation_space, spaces.Tuple)
assert len(env.observation_space) == 3
reset_obs = env.reset()
assert isinstance(reset_obs, list)
assert len(reset_obs) == 3
assert all(isinstance(ob, np.ndarray) for ob in reset_obs)
assert reset_obs[-1].shape == (3,)
actions = env.action_space.sample()
assert actions.shape == (2,)
obs, rew, done, info = env.step(actions)
assert all(isinstance(ob, np.ndarray) for ob in obs)
assert isinstance(rew, float)
assert isinstance(done, (bool, np.bool_))
assert isinstance(info, dict)
# check behavior for allow_multiple_obs = False
env = UnityToGymWrapper(mock_env, uint8_visual=use_uint8, allow_multiple_obs=False)
assert isinstance(env.observation_space, spaces.Box)
reset_obs = env.reset()
assert isinstance(reset_obs, np.ndarray)
assert len(reset_obs.shape) == 3
actions = env.action_space.sample()
assert actions.shape == (2,)
obs, rew, done, info = env.step(actions)
assert isinstance(obs, np.ndarray)
# Helper methods
def create_mock_group_spec(
number_visual_observations=0,
vector_action_space_type="continuous",
vector_observation_space_size=3,
vector_action_space_size=None,
):
"""
Creates a mock BrainParameters object with parameters.
"""
# Avoid using mutable object as default param
if vector_action_space_type == "continuous":
if vector_action_space_size is None:
vector_action_space_size = 2
else:
vector_action_space_size = vector_action_space_size[0]
action_spec = ActionSpec.create_continuous(vector_action_space_size)
else:
if vector_action_space_size is None:
vector_action_space_size = (2,)
else:
vector_action_space_size = tuple(vector_action_space_size)
action_spec = ActionSpec.create_discrete(vector_action_space_size)
obs_shapes = [(vector_observation_space_size,)]
for _ in range(number_visual_observations):
obs_shapes += [(8, 8, 3)]
obs_spec = create_observation_specs_with_shapes(obs_shapes)
return BehaviorSpec(obs_spec, action_spec)
def create_mock_vector_steps(specs, num_agents=1, number_visual_observations=0):
"""
Creates a mock BatchedStepResult with vector observations. Imitates constant
vector observations, rewards, dones, and agents.
:BehaviorSpecs specs: The BehaviorSpecs for this mock
:int num_agents: Number of "agents" to imitate in your BatchedStepResult values.
"""
obs = [np.array([num_agents * [1, 2, 3]], dtype=np.float32).reshape(num_agents, 3)]
if number_visual_observations:
obs += [
np.zeros(shape=(num_agents, 8, 8, 3), dtype=np.float32)
] * number_visual_observations
rewards = np.array(num_agents * [1.0])
agents = np.array(range(0, num_agents))
group_id = np.array(num_agents * [0])
group_rewards = np.array(num_agents * [0.0])
return (
DecisionSteps(obs, rewards, agents, None, group_id, group_rewards),
TerminalSteps.empty(specs),
)
def setup_mock_unityenvironment(mock_env, mock_spec, mock_decision, mock_termination):
"""
Takes a mock UnityEnvironment and adds the appropriate properties, defined by the mock
GroupSpec and BatchedStepResult.
:Mock mock_env: A mock UnityEnvironment, usually empty.
:Mock mock_spec: An AgentGroupSpec object that specifies the params of this environment.
:Mock mock_decision: A DecisionSteps object that will be returned at each step and reset.
:Mock mock_termination: A TerminationSteps object that will be returned at each step and reset.
"""
mock_env.behavior_specs = BehaviorMapping({"MockBrain": mock_spec})
mock_env.get_steps.return_value = (mock_decision, mock_termination)
| ml-agents/ml-agents-envs/tests/test_gym.py/0 | {
"file_path": "ml-agents/ml-agents-envs/tests/test_gym.py",
"repo_id": "ml-agents",
"token_count": 4128
} | 2,040 |
from typing import Optional
_rank: Optional[int] = None
def get_rank() -> Optional[int]:
"""
Returns the rank (in the MPI sense) of the current node.
For local training, this will always be None.
If this needs to be used, it should be done from outside ml-agents.
:return:
"""
return _rank
| ml-agents/ml-agents/mlagents/torch_utils/globals.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/torch_utils/globals.py",
"repo_id": "ml-agents",
"token_count": 106
} | 2,041 |
# # Unity ML-Agents Toolkit
from mlagents import torch_utils
import yaml
import os
import numpy as np
import json
from typing import Callable, Optional, List
import mlagents.trainers
import mlagents_envs
from mlagents.trainers.trainer_controller import TrainerController
from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager
from mlagents.trainers.trainer import TrainerFactory
from mlagents.trainers.directory_utils import (
validate_existing_directories,
setup_init_path,
)
from mlagents.trainers.stats import StatsReporter
from mlagents.trainers.cli_utils import parser
from mlagents_envs.environment import UnityEnvironment
from mlagents.trainers.settings import RunOptions
from mlagents.trainers.training_status import GlobalTrainingStatus
from mlagents_envs.base_env import BaseEnv
from mlagents.trainers.subprocess_env_manager import SubprocessEnvManager
from mlagents_envs.side_channel.side_channel import SideChannel
from mlagents_envs.timers import (
hierarchical_timer,
get_timer_tree,
add_metadata as add_timer_metadata,
)
from mlagents_envs import logging_util
from mlagents.plugins.stats_writer import register_stats_writer_plugins
from mlagents.plugins.trainer_type import register_trainer_plugins
logger = logging_util.get_logger(__name__)
TRAINING_STATUS_FILE_NAME = "training_status.json"
def get_version_string() -> str:
return f""" Version information:
ml-agents: {mlagents.trainers.__version__},
ml-agents-envs: {mlagents_envs.__version__},
Communicator API: {UnityEnvironment.API_VERSION},
PyTorch: {torch_utils.torch.__version__}"""
def parse_command_line(
argv: Optional[List[str]] = None,
) -> RunOptions:
_, _ = register_trainer_plugins()
args = parser.parse_args(argv)
return RunOptions.from_argparse(args)
def run_training(run_seed: int, options: RunOptions, num_areas: int) -> None:
"""
Launches training session.
:param run_seed: Random seed used for training.
:param num_areas: Number of training areas to instantiate
:param options: parsed command line arguments
"""
with hierarchical_timer("run_training.setup"):
torch_utils.set_torch_config(options.torch_settings)
checkpoint_settings = options.checkpoint_settings
env_settings = options.env_settings
engine_settings = options.engine_settings
run_logs_dir = checkpoint_settings.run_logs_dir
port: Optional[int] = env_settings.base_port
# Check if directory exists
validate_existing_directories(
checkpoint_settings.write_path,
checkpoint_settings.resume,
checkpoint_settings.force,
checkpoint_settings.maybe_init_path,
)
# Make run logs directory
os.makedirs(run_logs_dir, exist_ok=True)
# Load any needed states in case of resume
if checkpoint_settings.resume:
GlobalTrainingStatus.load_state(
os.path.join(run_logs_dir, "training_status.json")
)
# In case of initialization, set full init_path for all behaviors
elif checkpoint_settings.maybe_init_path is not None:
setup_init_path(options.behaviors, checkpoint_settings.maybe_init_path)
# Configure Tensorboard Writers and StatsReporter
stats_writers = register_stats_writer_plugins(options)
for sw in stats_writers:
StatsReporter.add_writer(sw)
if env_settings.env_path is None:
port = None
env_factory = create_environment_factory(
env_settings.env_path,
engine_settings.no_graphics,
engine_settings.no_graphics_monitor,
run_seed,
num_areas,
env_settings.timeout_wait,
port,
env_settings.env_args,
os.path.abspath(run_logs_dir), # Unity environment requires absolute path
)
env_manager = SubprocessEnvManager(env_factory, options, env_settings.num_envs)
env_parameter_manager = EnvironmentParameterManager(
options.environment_parameters, run_seed, restore=checkpoint_settings.resume
)
trainer_factory = TrainerFactory(
trainer_config=options.behaviors,
output_path=checkpoint_settings.write_path,
train_model=not checkpoint_settings.inference,
load_model=checkpoint_settings.resume,
seed=run_seed,
param_manager=env_parameter_manager,
init_path=checkpoint_settings.maybe_init_path,
multi_gpu=False,
)
# Create controller and begin training.
tc = TrainerController(
trainer_factory,
checkpoint_settings.write_path,
checkpoint_settings.run_id,
env_parameter_manager,
not checkpoint_settings.inference,
run_seed,
)
# Begin training
try:
tc.start_learning(env_manager)
finally:
env_manager.close()
write_run_options(checkpoint_settings.write_path, options)
write_timing_tree(run_logs_dir)
write_training_status(run_logs_dir)
def write_run_options(output_dir: str, run_options: RunOptions) -> None:
run_options_path = os.path.join(output_dir, "configuration.yaml")
try:
with open(run_options_path, "w") as f:
try:
yaml.dump(run_options.as_dict(), f, sort_keys=False)
except TypeError: # Older versions of pyyaml don't support sort_keys
yaml.dump(run_options.as_dict(), f)
except FileNotFoundError:
logger.warning(
f"Unable to save configuration to {run_options_path}. Make sure the directory exists"
)
def write_training_status(output_dir: str) -> None:
GlobalTrainingStatus.save_state(os.path.join(output_dir, TRAINING_STATUS_FILE_NAME))
def write_timing_tree(output_dir: str) -> None:
timing_path = os.path.join(output_dir, "timers.json")
try:
with open(timing_path, "w") as f:
json.dump(get_timer_tree(), f, indent=4)
except FileNotFoundError:
logger.warning(
f"Unable to save to {timing_path}. Make sure the directory exists"
)
def create_environment_factory(
env_path: Optional[str],
no_graphics: bool,
no_graphics_monitor: bool,
seed: int,
num_areas: int,
timeout_wait: int,
start_port: Optional[int],
env_args: Optional[List[str]],
log_folder: str,
) -> Callable[[int, List[SideChannel]], BaseEnv]:
def create_unity_environment(
worker_id: int, side_channels: List[SideChannel]
) -> UnityEnvironment:
# Make sure that each environment gets a different seed
env_seed = seed + worker_id
return UnityEnvironment(
file_name=env_path,
worker_id=worker_id,
seed=env_seed,
num_areas=num_areas,
no_graphics=no_graphics,
no_graphics_monitor=no_graphics_monitor,
base_port=start_port,
additional_args=env_args,
side_channels=side_channels,
log_folder=log_folder,
timeout_wait=timeout_wait,
)
return create_unity_environment
def run_cli(options: RunOptions) -> None:
try:
print(
"""
┐ ╖
╓╖╬│╡ ││╬╖╖
╓╖╬│││││┘ ╬│││││╬╖
╖╬│││││╬╜ ╙╬│││││╖╖ ╗╗╗
╬╬╬╬╖││╦╖ ╖╬││╗╣╣╣╬ ╟╣╣╬ ╟╣╣╣ ╜╜╜ ╟╣╣
╬╬╬╬╬╬╬╬╖│╬╖╖╓╬╪│╓╣╣╣╣╣╣╣╬ ╟╣╣╬ ╟╣╣╣ ╒╣╣╖╗╣╣╣╗ ╣╣╣ ╣╣╣╣╣╣ ╟╣╣╖ ╣╣╣
╬╬╬╬┐ ╙╬╬╬╬│╓╣╣╣╝╜ ╫╣╣╣╬ ╟╣╣╬ ╟╣╣╣ ╟╣╣╣╙ ╙╣╣╣ ╣╣╣ ╙╟╣╣╜╙ ╫╣╣ ╟╣╣
╬╬╬╬┐ ╙╬╬╣╣ ╫╣╣╣╬ ╟╣╣╬ ╟╣╣╣ ╟╣╣╬ ╣╣╣ ╣╣╣ ╟╣╣ ╣╣╣┌╣╣╜
╬╬╬╜ ╬╬╣╣ ╙╝╣╣╬ ╙╣╣╣╗╖╓╗╣╣╣╜ ╟╣╣╬ ╣╣╣ ╣╣╣ ╟╣╣╦╓ ╣╣╣╣╣
╙ ╓╦╖ ╬╬╣╣ ╓╗╗╖ ╙╝╣╣╣╣╝╜ ╘╝╝╜ ╝╝╝ ╝╝╝ ╙╣╣╣ ╟╣╣╣
╩╬╬╬╬╬╬╦╦╬╬╣╣╗╣╣╣╣╣╣╣╝ ╫╣╣╣╣
╙╬╬╬╬╬╬╬╣╣╣╣╣╣╝╜
╙╬╬╬╣╣╣╜
╙
"""
)
except Exception:
print("\n\n\tUnity Technologies\n")
print(get_version_string())
if options.debug:
log_level = logging_util.DEBUG
else:
log_level = logging_util.INFO
logging_util.set_log_level(log_level)
logger.debug("Configuration for this run:")
logger.debug(json.dumps(options.as_dict(), indent=4))
# Options deprecation warnings
if options.checkpoint_settings.load_model:
logger.warning(
"The --load option has been deprecated. Please use the --resume option instead."
)
if options.checkpoint_settings.train_model:
logger.warning(
"The --train option has been deprecated. Train mode is now the default. Use "
"--inference to run in inference mode."
)
run_seed = options.env_settings.seed
num_areas = options.env_settings.num_areas
# Add some timer metadata
add_timer_metadata("mlagents_version", mlagents.trainers.__version__)
add_timer_metadata("mlagents_envs_version", mlagents_envs.__version__)
add_timer_metadata("communication_protocol_version", UnityEnvironment.API_VERSION)
add_timer_metadata("pytorch_version", torch_utils.torch.__version__)
add_timer_metadata("numpy_version", np.__version__)
if options.env_settings.seed == -1:
run_seed = np.random.randint(0, 10000)
logger.debug(f"run_seed set to {run_seed}")
run_training(run_seed, options, num_areas)
def main():
run_cli(parse_command_line())
# For python debugger to directly run this script
if __name__ == "__main__":
main()
| ml-agents/ml-agents/mlagents/trainers/learn.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/learn.py",
"repo_id": "ml-agents",
"token_count": 4724
} | 2,042 |
# # Unity ML-Agents Toolkit
# ## ML-Agent Learning (PPO)
# Contains an implementation of PPO as described in: https://arxiv.org/abs/1707.06347
from typing import cast, Type, Union, Dict, Any
import numpy as np
from mlagents_envs.base_env import BehaviorSpec
from mlagents_envs.logging_util import get_logger
from mlagents.trainers.buffer import BufferKey, RewardSignalUtil
from mlagents.trainers.trainer.on_policy_trainer import OnPolicyTrainer
from mlagents.trainers.policy.policy import Policy
from mlagents.trainers.trainer.trainer_utils import get_gae
from mlagents.trainers.optimizer.torch_optimizer import TorchOptimizer
from mlagents.trainers.policy.torch_policy import TorchPolicy
from mlagents.trainers.ppo.optimizer_torch import TorchPPOOptimizer, PPOSettings
from mlagents.trainers.trajectory import Trajectory
from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers
from mlagents.trainers.settings import TrainerSettings
from mlagents.trainers.torch_entities.networks import SimpleActor, SharedActorCritic
logger = get_logger(__name__)
TRAINER_NAME = "ppo"
class PPOTrainer(OnPolicyTrainer):
"""The PPOTrainer is an implementation of the PPO algorithm."""
def __init__(
self,
behavior_name: str,
reward_buff_cap: int,
trainer_settings: TrainerSettings,
training: bool,
load: bool,
seed: int,
artifact_path: str,
):
"""
Responsible for collecting experiences and training PPO model.
:param behavior_name: The name of the behavior associated with trainer config
:param reward_buff_cap: Max reward history to track in the reward buffer
:param trainer_settings: The parameters for the trainer.
:param training: Whether the trainer is set for training.
:param load: Whether the model should be loaded.
:param seed: The seed the model will be initialized with
:param artifact_path: The directory within which to store artifacts from this trainer.
"""
super().__init__(
behavior_name,
reward_buff_cap,
trainer_settings,
training,
load,
seed,
artifact_path,
)
self.hyperparameters: PPOSettings = cast(
PPOSettings, self.trainer_settings.hyperparameters
)
self.seed = seed
self.shared_critic = self.hyperparameters.shared_critic
self.policy: TorchPolicy = None # type: ignore
def _process_trajectory(self, trajectory: Trajectory) -> None:
"""
Takes a trajectory and processes it, putting it into the update buffer.
Processing involves calculating value and advantage targets for model updating step.
:param trajectory: The Trajectory tuple containing the steps to be processed.
"""
super()._process_trajectory(trajectory)
agent_id = trajectory.agent_id # All the agents should have the same ID
agent_buffer_trajectory = trajectory.to_agentbuffer()
# Check if we used group rewards, warn if so.
self._warn_if_group_reward(agent_buffer_trajectory)
# Update the normalization
if self.is_training:
self.policy.actor.update_normalization(agent_buffer_trajectory)
self.optimizer.critic.update_normalization(agent_buffer_trajectory)
# Get all value estimates
(
value_estimates,
value_next,
value_memories,
) = self.optimizer.get_trajectory_value_estimates(
agent_buffer_trajectory,
trajectory.next_obs,
trajectory.done_reached and not trajectory.interrupted,
)
if value_memories is not None:
agent_buffer_trajectory[BufferKey.CRITIC_MEMORY].set(value_memories)
for name, v in value_estimates.items():
agent_buffer_trajectory[RewardSignalUtil.value_estimates_key(name)].extend(
v
)
self._stats_reporter.add_stat(
f"Policy/{self.optimizer.reward_signals[name].name.capitalize()} Value Estimate",
np.mean(v),
)
# Evaluate all reward functions
self.collected_rewards["environment"][agent_id] += np.sum(
agent_buffer_trajectory[BufferKey.ENVIRONMENT_REWARDS]
)
for name, reward_signal in self.optimizer.reward_signals.items():
evaluate_result = (
reward_signal.evaluate(agent_buffer_trajectory) * reward_signal.strength
)
agent_buffer_trajectory[RewardSignalUtil.rewards_key(name)].extend(
evaluate_result
)
# Report the reward signals
self.collected_rewards[name][agent_id] += np.sum(evaluate_result)
# Compute GAE and returns
tmp_advantages = []
tmp_returns = []
for name in self.optimizer.reward_signals:
bootstrap_value = value_next[name]
local_rewards = agent_buffer_trajectory[
RewardSignalUtil.rewards_key(name)
].get_batch()
local_value_estimates = agent_buffer_trajectory[
RewardSignalUtil.value_estimates_key(name)
].get_batch()
local_advantage = get_gae(
rewards=local_rewards,
value_estimates=local_value_estimates,
value_next=bootstrap_value,
gamma=self.optimizer.reward_signals[name].gamma,
lambd=self.hyperparameters.lambd,
)
local_return = local_advantage + local_value_estimates
# This is later use as target for the different value estimates
agent_buffer_trajectory[RewardSignalUtil.returns_key(name)].set(
local_return
)
agent_buffer_trajectory[RewardSignalUtil.advantage_key(name)].set(
local_advantage
)
tmp_advantages.append(local_advantage)
tmp_returns.append(local_return)
# Get global advantages
global_advantages = list(
np.mean(np.array(tmp_advantages, dtype=np.float32), axis=0)
)
global_returns = list(np.mean(np.array(tmp_returns, dtype=np.float32), axis=0))
agent_buffer_trajectory[BufferKey.ADVANTAGES].set(global_advantages)
agent_buffer_trajectory[BufferKey.DISCOUNTED_RETURNS].set(global_returns)
self._append_to_update_buffer(agent_buffer_trajectory)
# If this was a terminal trajectory, append stats and reset reward collection
if trajectory.done_reached:
self._update_end_episode_stats(agent_id, self.optimizer)
def create_optimizer(self) -> TorchOptimizer:
return TorchPPOOptimizer( # type: ignore
cast(TorchPolicy, self.policy), self.trainer_settings # type: ignore
) # type: ignore
def create_policy(
self, parsed_behavior_id: BehaviorIdentifiers, behavior_spec: BehaviorSpec
) -> TorchPolicy:
"""
Creates a policy with a PyTorch backend and PPO hyperparameters
:param parsed_behavior_id:
:param behavior_spec: specifications for policy construction
:return policy
"""
actor_cls: Union[Type[SimpleActor], Type[SharedActorCritic]] = SimpleActor
actor_kwargs: Dict[str, Any] = {
"conditional_sigma": False,
"tanh_squash": False,
}
if self.shared_critic:
reward_signal_configs = self.trainer_settings.reward_signals
reward_signal_names = [
key.value for key, _ in reward_signal_configs.items()
]
actor_cls = SharedActorCritic
actor_kwargs.update({"stream_names": reward_signal_names})
policy = TorchPolicy(
self.seed,
behavior_spec,
self.trainer_settings.network_settings,
actor_cls,
actor_kwargs,
)
return policy
def get_policy(self, name_behavior_id: str) -> Policy:
"""
Gets policy from trainer associated with name_behavior_id
:param name_behavior_id: full identifier of policy
"""
return self.policy
@staticmethod
def get_trainer_name() -> str:
return TRAINER_NAME
| ml-agents/ml-agents/mlagents/trainers/ppo/trainer.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/ppo/trainer.py",
"repo_id": "ml-agents",
"token_count": 3600
} | 2,043 |
from unittest import mock
import pytest
from typing import List
import mlagents.trainers.tests.mock_brain as mb
import numpy as np
from mlagents.trainers.agent_processor import (
AgentProcessor,
AgentManager,
AgentManagerQueue,
)
from mlagents.trainers.action_info import ActionInfo
from mlagents.trainers.torch_entities.action_log_probs import LogProbsTuple
from mlagents.trainers.trajectory import Trajectory
from mlagents.trainers.stats import StatsReporter, StatsSummary
from mlagents.trainers.behavior_id_utils import get_global_agent_id
from mlagents_envs.side_channel.stats_side_channel import StatsAggregationMethod
from mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes
from mlagents_envs.base_env import ActionSpec, ActionTuple
def create_mock_policy():
mock_policy = mock.Mock()
mock_policy.reward_signals = {}
mock_policy.retrieve_previous_memories.return_value = np.zeros(
(1, 1), dtype=np.float32
)
mock_policy.retrieve_previous_action.return_value = np.zeros((1, 1), dtype=np.int32)
return mock_policy
def _create_action_info(num_agents: int, agent_ids: List[str]) -> ActionInfo:
fake_action_outputs = {
"action": ActionTuple(
continuous=np.array([[0.1]] * num_agents, dtype=np.float32)
),
"entropy": np.array([1.0], dtype=np.float32),
"learning_rate": 1.0,
"log_probs": LogProbsTuple(
continuous=np.array([[0.1]] * num_agents, dtype=np.float32)
),
}
fake_action_info = ActionInfo(
action=ActionTuple(continuous=np.array([[0.1]] * num_agents, dtype=np.float32)),
env_action=ActionTuple(
continuous=np.array([[0.1]] * num_agents, dtype=np.float32)
),
outputs=fake_action_outputs,
agent_ids=agent_ids,
)
return fake_action_info
@pytest.mark.parametrize("num_vis_obs", [0, 1, 2], ids=["vec", "1 viz", "2 viz"])
def test_agentprocessor(num_vis_obs):
policy = create_mock_policy()
tqueue = mock.Mock()
name_behavior_id = "test_brain_name"
processor = AgentProcessor(
policy,
name_behavior_id,
max_trajectory_length=5,
stats_reporter=StatsReporter("testcat"),
)
mock_decision_steps, mock_terminal_steps = mb.create_mock_steps(
num_agents=2,
observation_specs=create_observation_specs_with_shapes(
[(8,)] + num_vis_obs * [(84, 84, 3)]
),
action_spec=ActionSpec.create_continuous(2),
)
fake_action_info = _create_action_info(2, mock_decision_steps.agent_id)
processor.publish_trajectory_queue(tqueue)
# This is like the initial state after the env reset
processor.add_experiences(
mock_decision_steps, mock_terminal_steps, 0, ActionInfo.empty()
)
for _ in range(5):
processor.add_experiences(
mock_decision_steps, mock_terminal_steps, 0, fake_action_info
)
# Assert that two trajectories have been added to the Trainer
assert len(tqueue.put.call_args_list) == 2
# Assert that the trajectory is of length 5
trajectory = tqueue.put.call_args_list[0][0][0]
assert len(trajectory.steps) == 5
# Make sure ungrouped agents don't have team obs
for step in trajectory.steps:
assert len(step.group_status) == 0
# Assert that the AgentProcessor is empty
assert len(processor._experience_buffers[0]) == 0
# Test empty steps
mock_decision_steps, mock_terminal_steps = mb.create_mock_steps(
num_agents=0,
observation_specs=create_observation_specs_with_shapes(
[(8,)] + num_vis_obs * [(84, 84, 3)]
),
action_spec=ActionSpec.create_continuous(2),
)
processor.add_experiences(
mock_decision_steps, mock_terminal_steps, 0, ActionInfo.empty()
)
# Assert that the AgentProcessor is still empty
assert len(processor._experience_buffers[0]) == 0
def test_group_statuses():
policy = create_mock_policy()
tqueue = mock.Mock()
name_behavior_id = "test_brain_name"
processor = AgentProcessor(
policy,
name_behavior_id,
max_trajectory_length=5,
stats_reporter=StatsReporter("testcat"),
)
mock_decision_steps, mock_terminal_steps = mb.create_mock_steps(
num_agents=4,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
grouped=True,
)
fake_action_info = _create_action_info(4, mock_decision_steps.agent_id)
processor.publish_trajectory_queue(tqueue)
# This is like the initial state after the env reset
processor.add_experiences(
mock_decision_steps, mock_terminal_steps, 0, ActionInfo.empty()
)
for _ in range(2):
processor.add_experiences(
mock_decision_steps, mock_terminal_steps, 0, fake_action_info
)
# Make terminal steps for some dead agents
_, mock_terminal_steps_2 = mb.create_mock_steps(
num_agents=2,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
done=True,
grouped=True,
agent_ids=[2, 3],
)
# Make decision steps continue for other agents
mock_decision_steps_2, _ = mb.create_mock_steps(
num_agents=2,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
done=False,
grouped=True,
agent_ids=[0, 1],
)
processor.add_experiences(
mock_decision_steps_2, mock_terminal_steps_2, 0, fake_action_info
)
# Continue to add for remaining live agents
fake_action_info = _create_action_info(4, mock_decision_steps_2.agent_id)
for _ in range(3):
processor.add_experiences(
mock_decision_steps_2, mock_terminal_steps, 0, fake_action_info
)
# Assert that four trajectories have been added to the Trainer
assert len(tqueue.put.call_args_list) == 4
# Get the first trajectory, which should have been agent 2 (one of the killed agents)
trajectory = tqueue.put.call_args_list[0][0][-1]
assert len(trajectory.steps) == 3
# Make sure trajectory has the right Groupmate Experiences.
# All three steps should contain all agents
for step in trajectory.steps:
assert len(step.group_status) == 3
# Last trajectory should be the longest. It should be that of agent 1, one of the surviving agents.
trajectory = tqueue.put.call_args_list[-1][0][-1]
assert len(trajectory.steps) == 5
# Make sure trajectory has the right Groupmate Experiences.
# THe first 3 steps should contain all of the obs (that 3rd step is also the terminal step of 2 of the agents)
for step in trajectory.steps[0:3]:
assert len(step.group_status) == 3
# After 2 agents has died, there should only be 1 group status.
for step in trajectory.steps[3:]:
assert len(step.group_status) == 1
def test_agent_deletion():
policy = create_mock_policy()
tqueue = mock.Mock()
name_behavior_id = "test_brain_name"
processor = AgentProcessor(
policy,
name_behavior_id,
max_trajectory_length=5,
stats_reporter=StatsReporter("testcat"),
)
fake_action_outputs = {
"action": ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
"entropy": np.array([1.0], dtype=np.float32),
"learning_rate": 1.0,
"log_probs": LogProbsTuple(continuous=np.array([[0.1]], dtype=np.float32)),
}
mock_decision_step, mock_terminal_step = mb.create_mock_steps(
num_agents=1,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
)
mock_done_decision_step, mock_done_terminal_step = mb.create_mock_steps(
num_agents=1,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
done=True,
)
fake_action_info = ActionInfo(
action=ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
env_action=ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
outputs=fake_action_outputs,
agent_ids=mock_decision_step.agent_id,
)
processor.publish_trajectory_queue(tqueue)
# This is like the initial state after the env reset
processor.add_experiences(
mock_decision_step, mock_terminal_step, 0, ActionInfo.empty()
)
# Run 3 trajectories, with different workers (to simulate different agents)
add_calls = []
remove_calls = []
for _ep in range(3):
for _ in range(5):
processor.add_experiences(
mock_decision_step, mock_terminal_step, _ep, fake_action_info
)
add_calls.append(
mock.call([get_global_agent_id(_ep, 0)], fake_action_outputs["action"])
)
processor.add_experiences(
mock_done_decision_step, mock_done_terminal_step, _ep, fake_action_info
)
# Make sure we don't add experiences from the prior agents after the done
remove_calls.append(mock.call([get_global_agent_id(_ep, 0)]))
policy.save_previous_action.assert_has_calls(add_calls)
policy.remove_previous_action.assert_has_calls(remove_calls)
# Check that there are no experiences left
assert len(processor._experience_buffers.keys()) == 0
assert len(processor._last_take_action_outputs.keys()) == 0
assert len(processor._episode_steps.keys()) == 0
assert len(processor._episode_rewards.keys()) == 0
assert len(processor._last_step_result.keys()) == 0
# check that steps with immediate dones don't add to dicts
processor.add_experiences(
mock_done_decision_step, mock_done_terminal_step, 0, ActionInfo.empty()
)
assert len(processor._experience_buffers.keys()) == 0
assert len(processor._last_take_action_outputs.keys()) == 0
assert len(processor._episode_steps.keys()) == 0
assert len(processor._episode_rewards.keys()) == 0
assert len(processor._last_step_result.keys()) == 0
def test_end_episode():
policy = create_mock_policy()
tqueue = mock.Mock()
name_behavior_id = "test_brain_name"
processor = AgentProcessor(
policy,
name_behavior_id,
max_trajectory_length=5,
stats_reporter=StatsReporter("testcat"),
)
fake_action_outputs = {
"action": ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
"entropy": np.array([1.0], dtype=np.float32),
"learning_rate": 1.0,
"log_probs": LogProbsTuple(continuous=np.array([[0.1]], dtype=np.float32)),
}
mock_decision_step, mock_terminal_step = mb.create_mock_steps(
num_agents=1,
observation_specs=create_observation_specs_with_shapes([(8,)]),
action_spec=ActionSpec.create_continuous(2),
)
fake_action_info = ActionInfo(
action=ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
env_action=ActionTuple(continuous=np.array([[0.1]], dtype=np.float32)),
outputs=fake_action_outputs,
agent_ids=mock_decision_step.agent_id,
)
processor.publish_trajectory_queue(tqueue)
# This is like the initial state after the env reset
processor.add_experiences(
mock_decision_step, mock_terminal_step, 0, ActionInfo.empty()
)
# Run 3 trajectories, with different workers (to simulate different agents)
remove_calls = []
for _ep in range(3):
remove_calls.append(mock.call([get_global_agent_id(_ep, 0)]))
for _ in range(5):
processor.add_experiences(
mock_decision_step, mock_terminal_step, _ep, fake_action_info
)
# Make sure we don't add experiences from the prior agents after the done
# Call end episode
processor.end_episode()
# Check that we removed every agent
policy.remove_previous_action.assert_has_calls(remove_calls)
# Check that there are no experiences left
assert len(processor._experience_buffers.keys()) == 0
assert len(processor._last_take_action_outputs.keys()) == 0
assert len(processor._episode_steps.keys()) == 0
assert len(processor._episode_rewards.keys()) == 0
def test_agent_manager():
policy = create_mock_policy()
name_behavior_id = "test_brain_name"
manager = AgentManager(
policy,
name_behavior_id,
max_trajectory_length=5,
stats_reporter=StatsReporter("testcat"),
)
assert len(manager._trajectory_queues) == 1
assert isinstance(manager._trajectory_queues[0], AgentManagerQueue)
def test_agent_manager_queue():
queue = AgentManagerQueue(behavior_id="testbehavior")
trajectory = mock.Mock(spec=Trajectory)
assert queue.empty()
queue.put(trajectory)
assert not queue.empty()
queue_traj = queue.get_nowait()
assert isinstance(queue_traj, Trajectory)
assert queue.empty()
def test_agent_manager_stats():
policy = mock.Mock()
stats_reporter = StatsReporter("FakeCategory")
writer = mock.Mock()
stats_reporter.add_writer(writer)
manager = AgentManager(policy, "MyBehavior", stats_reporter)
all_env_stats = [
{
"averaged": [(1.0, StatsAggregationMethod.AVERAGE)],
"most_recent": [(2.0, StatsAggregationMethod.MOST_RECENT)],
"summed": [(3.1, StatsAggregationMethod.SUM)],
},
{
"averaged": [(3.0, StatsAggregationMethod.AVERAGE)],
"most_recent": [(4.0, StatsAggregationMethod.MOST_RECENT)],
"summed": [(1.1, StatsAggregationMethod.SUM)],
},
]
for env_stats in all_env_stats:
manager.record_environment_stats(env_stats, worker_id=0)
expected_stats = {
"averaged": StatsSummary(
full_dist=[1.0, 3.0], aggregation_method=StatsAggregationMethod.AVERAGE
),
"most_recent": StatsSummary(
full_dist=[4.0], aggregation_method=StatsAggregationMethod.MOST_RECENT
),
"summed": StatsSummary(
full_dist=[3.1, 1.1], aggregation_method=StatsAggregationMethod.SUM
),
}
stats_reporter.write_stats(123)
writer.write_stats.assert_any_call("FakeCategory", expected_stats, 123)
# clean up our Mock from the global list
StatsReporter.writers.remove(writer)
| ml-agents/ml-agents/mlagents/trainers/tests/test_agent_processor.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_agent_processor.py",
"repo_id": "ml-agents",
"token_count": 6009
} | 2,044 |
import pytest
import io
import os
import yaml
from unittest.mock import patch
from mlagents.trainers.trainer import TrainerFactory
from mlagents.trainers.cli_utils import load_config, _load_config
from mlagents.trainers.ppo.trainer import PPOTrainer
from mlagents.trainers.exception import TrainerConfigError, UnityTrainerException
from mlagents.trainers.settings import RunOptions
from mlagents.trainers.tests.dummy_config import ppo_dummy_config
from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager
from mlagents.trainers.directory_utils import (
validate_existing_directories,
setup_init_path,
)
@pytest.fixture
def dummy_config():
return RunOptions(behaviors={"testbrain": ppo_dummy_config()})
@patch("mlagents_envs.base_env.BehaviorSpec")
def test_initialize_ppo_trainer(BehaviorSpecMock, dummy_config):
brain_name = "testbrain"
training_behaviors = {"testbrain": BehaviorSpecMock()}
output_path = "results_dir"
train_model = True
load_model = False
seed = 11
expected_reward_buff_cap = 1
base_config = dummy_config.behaviors
expected_config = ppo_dummy_config()
def mock_constructor(
self,
brain,
reward_buff_cap,
trainer_settings,
training,
load,
p_seed,
artifact_path,
):
assert brain == brain_name
assert trainer_settings == expected_config
assert reward_buff_cap == expected_reward_buff_cap
assert training == train_model
assert load == load_model
assert p_seed == seed
assert artifact_path == os.path.join(output_path, brain_name)
with patch.object(PPOTrainer, "__init__", mock_constructor):
trainer_factory = TrainerFactory(
trainer_config=base_config,
output_path=output_path,
train_model=train_model,
load_model=load_model,
seed=seed,
param_manager=EnvironmentParameterManager(),
)
trainers = {}
for brain_name in training_behaviors.keys():
trainers[brain_name] = trainer_factory.generate(brain_name)
assert "testbrain" in trainers
assert isinstance(trainers["testbrain"], PPOTrainer)
def test_handles_no_config_provided():
"""
Make sure the trainer setup handles no configs provided at all.
"""
brain_name = "testbrain"
no_default_config = RunOptions().behaviors
# Pretend this was created without a YAML file
no_default_config.set_config_specified(False)
trainer_factory = TrainerFactory(
trainer_config=no_default_config,
output_path="output_path",
train_model=True,
load_model=False,
seed=42,
param_manager=EnvironmentParameterManager(),
)
trainer_factory.generate(brain_name)
def test_load_config_missing_file():
with pytest.raises(TrainerConfigError):
load_config("thisFileDefinitelyDoesNotExist.yaml")
def test_load_config_valid_yaml():
file_contents = """
this:
- is fine
"""
fp = io.StringIO(file_contents)
res = _load_config(fp)
assert res == {"this": ["is fine"]}
def test_load_config_invalid_yaml():
file_contents = """
you:
- will
- not
- parse
"""
with pytest.raises(TrainerConfigError):
fp = io.StringIO(file_contents)
_load_config(fp)
def test_existing_directories(tmp_path):
output_path = os.path.join(tmp_path, "runid")
# Test fresh new unused path - should do nothing.
validate_existing_directories(output_path, False, False)
# Test resume with fresh path - should throw an exception.
with pytest.raises(UnityTrainerException):
validate_existing_directories(output_path, True, False)
# make a directory
os.mkdir(output_path)
# Test try to train w.o. force, should complain
with pytest.raises(UnityTrainerException):
validate_existing_directories(output_path, False, False)
# Test try to train w/ resume - should work
validate_existing_directories(output_path, True, False)
# Test try to train w/ force - should work
validate_existing_directories(output_path, False, True)
# Test initialize option
init_path = os.path.join(tmp_path, "runid2")
with pytest.raises(UnityTrainerException):
validate_existing_directories(output_path, False, True, init_path)
os.mkdir(init_path)
# Should pass since the directory exists now.
validate_existing_directories(output_path, False, True, init_path)
@pytest.mark.parametrize("dir_exists", [True, False])
def test_setup_init_path(tmpdir, dir_exists):
"""
:return:
"""
init_path = os.path.join(
"{}",
"test_setup_init_path_results",
"test_run_id",
"MediumWallJump",
"checkpoint.pt",
)
test_yaml = f"""
behaviors:
BigWallJump:
init_path: BigWallJump-6540981.pt #full path
trainer_type: ppo
MediumWallJump:
init_path: {init_path}
trainer_type: ppo
SmallWallJump:
trainer_type: ppo
checkpoint_settings:
run_id: test_run_id
initialize_from: test_run_id
""".format(
tmpdir
)
run_options = RunOptions.from_dict(yaml.safe_load(test_yaml))
if dir_exists:
init_path = tmpdir.mkdir("test_setup_init_path_results").mkdir("test_run_id")
big = init_path.mkdir("BigWallJump").join("BigWallJump-6540981.pt")
big.write("content")
med = init_path.mkdir("MediumWallJump").join("checkpoint.pt")
med.write("content")
small = init_path.mkdir("SmallWallJump").join("checkpoint.pt")
small.write("content")
setup_init_path(run_options.behaviors, init_path)
assert run_options.behaviors["BigWallJump"].init_path == big
assert run_options.behaviors["MediumWallJump"].init_path == med
assert run_options.behaviors["SmallWallJump"].init_path == small
else:
# don't make dirs and fail
with pytest.raises(UnityTrainerException):
setup_init_path(
run_options.behaviors, run_options.checkpoint_settings.maybe_init_path
)
| ml-agents/ml-agents/mlagents/trainers/tests/test_trainer_util.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_trainer_util.py",
"repo_id": "ml-agents",
"token_count": 2515
} | 2,045 |
import pytest
from mlagents.torch_utils import torch
from mlagents.trainers.torch_entities.distributions import (
GaussianDistribution,
MultiCategoricalDistribution,
GaussianDistInstance,
TanhGaussianDistInstance,
CategoricalDistInstance,
)
@pytest.mark.parametrize("tanh_squash", [True, False])
@pytest.mark.parametrize("conditional_sigma", [True, False])
def test_gaussian_distribution(conditional_sigma, tanh_squash):
torch.manual_seed(0)
hidden_size = 16
act_size = 4
sample_embedding = torch.ones((1, 16))
gauss_dist = GaussianDistribution(
hidden_size,
act_size,
conditional_sigma=conditional_sigma,
tanh_squash=tanh_squash,
)
# Make sure backprop works
force_action = torch.zeros((1, act_size))
optimizer = torch.optim.Adam(gauss_dist.parameters(), lr=3e-3)
for _ in range(50):
dist_inst = gauss_dist(sample_embedding)
if tanh_squash:
assert isinstance(dist_inst, TanhGaussianDistInstance)
else:
assert isinstance(dist_inst, GaussianDistInstance)
log_prob = dist_inst.log_prob(force_action)
loss = torch.nn.functional.mse_loss(log_prob, -2 * torch.ones(log_prob.shape))
optimizer.zero_grad()
loss.backward()
optimizer.step()
for prob in log_prob.flatten().tolist():
assert prob == pytest.approx(-2, abs=0.1)
def test_multi_categorical_distribution():
torch.manual_seed(0)
hidden_size = 16
act_size = [3, 3, 4]
sample_embedding = torch.ones((1, 16))
gauss_dist = MultiCategoricalDistribution(hidden_size, act_size)
# Make sure backprop works
optimizer = torch.optim.Adam(gauss_dist.parameters(), lr=3e-3)
def create_test_prob(size: int) -> torch.Tensor:
test_prob = torch.tensor(
[[1.0 - 0.01 * (size - 1)] + [0.01] * (size - 1)]
) # High prob for first action
return test_prob.log()
for _ in range(100):
dist_insts = gauss_dist(sample_embedding, masks=torch.ones((1, sum(act_size))))
loss = 0
for i, dist_inst in enumerate(dist_insts):
assert isinstance(dist_inst, CategoricalDistInstance)
log_prob = dist_inst.all_log_prob()
test_log_prob = create_test_prob(act_size[i])
# Force log_probs to match the high probability for the first action generated by
# create_test_prob
loss += torch.nn.functional.mse_loss(log_prob, test_log_prob)
optimizer.zero_grad()
loss.backward()
optimizer.step()
for dist_inst, size in zip(dist_insts, act_size):
# Check that the log probs are close to the fake ones that we generated.
test_log_probs = create_test_prob(size)
for _prob, _test_prob in zip(
dist_inst.all_log_prob().flatten().tolist(),
test_log_probs.flatten().tolist(),
):
assert _prob == pytest.approx(_test_prob, abs=0.1)
# Test masks
masks = []
for branch in act_size:
masks += [0] * (branch - 1) + [1]
masks = torch.tensor([masks])
dist_insts = gauss_dist(sample_embedding, masks=masks)
for dist_inst in dist_insts:
log_prob = dist_inst.all_log_prob()
assert log_prob.flatten()[-1].tolist() == pytest.approx(0, abs=0.001)
def test_gaussian_dist_instance():
torch.manual_seed(0)
act_size = 4
dist_instance = GaussianDistInstance(
torch.zeros(1, act_size), torch.ones(1, act_size)
)
action = dist_instance.sample()
assert action.shape == (1, act_size)
for log_prob in (
dist_instance.log_prob(torch.zeros((1, act_size))).flatten().tolist()
):
# Log prob of standard normal at 0
assert log_prob == pytest.approx(-0.919, abs=0.01)
for ent in dist_instance.entropy().flatten().tolist():
# entropy of standard normal at 0, based on 1/2 + ln(sqrt(2pi)sigma)
assert ent == pytest.approx(1.42, abs=0.01)
def test_tanh_gaussian_dist_instance():
torch.manual_seed(0)
act_size = 4
dist_instance = TanhGaussianDistInstance(
torch.zeros(1, act_size), torch.ones(1, act_size)
)
for _ in range(10):
action = dist_instance.sample()
assert action.shape == (1, act_size)
assert torch.max(action) < 1.0 and torch.min(action) > -1.0
def test_categorical_dist_instance():
torch.manual_seed(0)
act_size = 4
test_prob = torch.tensor(
[[1.0 - 0.1 * (act_size - 1)] + [0.1] * (act_size - 1)]
) # High prob for first action
dist_instance = CategoricalDistInstance(test_prob)
for _ in range(10):
action = dist_instance.sample()
assert action.shape == (1, 1)
assert action < act_size
# Make sure the first action as higher probability than the others.
prob_first_action = dist_instance.log_prob(torch.tensor([0]))
for i in range(1, act_size):
assert dist_instance.log_prob(torch.tensor([i])) < prob_first_action
| ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_distributions.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_distributions.py",
"repo_id": "ml-agents",
"token_count": 2222
} | 2,046 |
import pytest
from mlagents.torch_utils import torch
import numpy as np
from mlagents.trainers.settings import EncoderType, ScheduleType
from mlagents.trainers.torch_entities.utils import ModelUtils
from mlagents.trainers.exception import UnityTrainerException
from mlagents.trainers.torch_entities.encoders import VectorInput
from mlagents.trainers.tests.dummy_config import create_observation_specs_with_shapes
def test_min_visual_size():
# Make sure each EncoderType has an entry in MIS_RESOLUTION_FOR_ENCODER
assert set(ModelUtils.MIN_RESOLUTION_FOR_ENCODER.keys()) == set(EncoderType)
for encoder_type in EncoderType:
good_size = ModelUtils.MIN_RESOLUTION_FOR_ENCODER[encoder_type]
vis_input = torch.ones((1, 3, good_size, good_size))
ModelUtils._check_resolution_for_encoder(good_size, good_size, encoder_type)
enc_func = ModelUtils.get_encoder_for_type(encoder_type)
enc = enc_func(good_size, good_size, 3, 1)
enc.forward(vis_input)
# Anything under the min size should raise an exception. If not, decrease the min size!
with pytest.raises(Exception):
bad_size = ModelUtils.MIN_RESOLUTION_FOR_ENCODER[encoder_type] - 1
vis_input = torch.ones((1, 3, bad_size, bad_size))
with pytest.raises(UnityTrainerException):
# Make sure we'd hit a friendly error during model setup time.
ModelUtils._check_resolution_for_encoder(
bad_size, bad_size, encoder_type
)
enc = enc_func(bad_size, bad_size, 3, 1)
enc.forward(vis_input)
@pytest.mark.parametrize(
"encoder_type",
[
EncoderType.SIMPLE,
EncoderType.NATURE_CNN,
EncoderType.SIMPLE,
EncoderType.MATCH3,
],
)
def test_invalid_visual_input_size(encoder_type):
with pytest.raises(UnityTrainerException):
obs_spec = create_observation_specs_with_shapes(
[
(
ModelUtils.MIN_RESOLUTION_FOR_ENCODER[encoder_type] - 1,
ModelUtils.MIN_RESOLUTION_FOR_ENCODER[encoder_type],
1,
)
]
)
ModelUtils.create_input_processors(obs_spec, 20, encoder_type, 20, False)
@pytest.mark.parametrize("num_visual", [0, 1, 2])
@pytest.mark.parametrize("num_vector", [0, 1, 2])
@pytest.mark.parametrize("normalize", [True, False])
@pytest.mark.parametrize("encoder_type", [EncoderType.SIMPLE, EncoderType.NATURE_CNN])
def test_create_inputs(encoder_type, normalize, num_vector, num_visual):
vec_obs_shape = (5,)
vis_obs_shape = (3, 84, 84)
obs_shapes = []
for _ in range(num_vector):
obs_shapes.append(vec_obs_shape)
for _ in range(num_visual):
obs_shapes.append(vis_obs_shape)
h_size = 128
obs_spec = create_observation_specs_with_shapes(obs_shapes)
encoders, embedding_sizes = ModelUtils.create_input_processors(
obs_spec, h_size, encoder_type, h_size, normalize
)
total_output = sum(embedding_sizes)
vec_enc = []
vis_enc = []
for i, enc in enumerate(encoders):
if len(obs_shapes[i]) == 1:
vec_enc.append(enc)
else:
vis_enc.append(enc)
assert len(vec_enc) == num_vector
assert len(vis_enc) == num_visual
assert total_output == int(num_visual * h_size + vec_obs_shape[0] * num_vector)
if num_vector > 0:
assert isinstance(vec_enc[0], VectorInput)
for enc in vis_enc:
assert isinstance(enc, ModelUtils.get_encoder_for_type(encoder_type))
def test_decayed_value():
test_steps = [0, 4, 9]
# Test constant decay
param = ModelUtils.DecayedValue(ScheduleType.CONSTANT, 1.0, 0.2, test_steps[-1])
for _step in test_steps:
_param = param.get_value(_step)
assert _param == 1.0
test_results = [1.0, 0.6444, 0.2]
# Test linear decay
param = ModelUtils.DecayedValue(ScheduleType.LINEAR, 1.0, 0.2, test_steps[-1])
for _step, _result in zip(test_steps, test_results):
_param = param.get_value(_step)
assert _param == pytest.approx(_result, abs=0.01)
# Test invalid
with pytest.raises(UnityTrainerException):
ModelUtils.DecayedValue(
"SomeOtherSchedule", 1.0, 0.2, test_steps[-1]
).get_value(0)
def test_polynomial_decay():
test_steps = [0, 4, 9]
test_results = [1.0, 0.7, 0.2]
for _step, _result in zip(test_steps, test_results):
decayed = ModelUtils.polynomial_decay(
1.0, 0.2, test_steps[-1], _step, power=0.8
)
assert decayed == pytest.approx(_result, abs=0.01)
def test_list_to_tensor():
# Test converting pure list
unconverted_list = [[1.0, 2], [1, 3], [1, 4]]
tensor = ModelUtils.list_to_tensor(unconverted_list)
# Should be equivalent to torch.tensor conversion
assert torch.equal(tensor, torch.tensor(unconverted_list))
# Test converting pure numpy array
np_list = np.asarray(unconverted_list)
tensor = ModelUtils.list_to_tensor(np_list)
# Should be equivalent to torch.tensor conversion
assert torch.equal(tensor, torch.tensor(unconverted_list))
# Test converting list of numpy arrays
list_of_np = [np.asarray(_el) for _el in unconverted_list]
tensor = ModelUtils.list_to_tensor(list_of_np)
# Should be equivalent to torch.tensor conversion
assert torch.equal(tensor, torch.tensor(unconverted_list, dtype=torch.float32))
def test_break_into_branches():
# Test normal multi-branch case
all_actions = torch.tensor([[1, 2, 3, 4, 5, 6]])
action_size = [2, 1, 3]
broken_actions = ModelUtils.break_into_branches(all_actions, action_size)
assert len(action_size) == len(broken_actions)
for i, _action in enumerate(broken_actions):
assert _action.shape == (1, action_size[i])
# Test 1-branch case
action_size = [6]
broken_actions = ModelUtils.break_into_branches(all_actions, action_size)
assert len(broken_actions) == 1
assert broken_actions[0].shape == (1, 6)
def test_actions_to_onehot():
all_actions = torch.tensor([[1, 0, 2], [1, 0, 2]])
action_size = [2, 1, 3]
oh_actions = ModelUtils.actions_to_onehot(all_actions, action_size)
expected_result = [
torch.tensor([[0, 1], [0, 1]], dtype=torch.float),
torch.tensor([[1], [1]], dtype=torch.float),
torch.tensor([[0, 0, 1], [0, 0, 1]], dtype=torch.float),
]
for res, exp in zip(oh_actions, expected_result):
assert torch.equal(res, exp)
def test_masked_mean():
test_input = torch.tensor([1, 2, 3, 4, 5])
masks = torch.ones_like(test_input).bool()
mean = ModelUtils.masked_mean(test_input, masks=masks)
assert mean == 3.0
masks = torch.tensor([False, False, True, True, True])
mean = ModelUtils.masked_mean(test_input, masks=masks)
assert mean == 4.0
# Make sure it works if all masks are off
masks = torch.tensor([False, False, False, False, False])
mean = ModelUtils.masked_mean(test_input, masks=masks)
assert mean == 0.0
# Make sure it works with 2d arrays of shape (mask_length, N)
test_input = torch.tensor([1, 2, 3, 4, 5]).repeat(2, 1).T
masks = torch.tensor([False, False, True, True, True])
mean = ModelUtils.masked_mean(test_input, masks=masks)
assert mean == 4.0
def test_soft_update():
class TestModule(torch.nn.Module):
def __init__(self, vals):
super().__init__()
self.parameter = torch.nn.Parameter(torch.ones(5, 5, 5) * vals)
tm1 = TestModule(0)
tm2 = TestModule(1)
tm3 = TestModule(2)
ModelUtils.soft_update(tm1, tm3, tau=0.5)
assert torch.equal(tm3.parameter, torch.ones(5, 5, 5))
ModelUtils.soft_update(tm1, tm2, tau=1.0)
assert torch.equal(tm2.parameter, tm1.parameter)
| ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_utils.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_utils.py",
"repo_id": "ml-agents",
"token_count": 3433
} | 2,047 |
from typing import Dict, Type
from mlagents.trainers.exception import UnityTrainerException
from mlagents.trainers.settings import RewardSignalSettings, RewardSignalType
from mlagents.trainers.torch_entities.components.reward_providers.base_reward_provider import (
BaseRewardProvider,
)
from mlagents.trainers.torch_entities.components.reward_providers.extrinsic_reward_provider import (
ExtrinsicRewardProvider,
)
from mlagents.trainers.torch_entities.components.reward_providers.curiosity_reward_provider import (
CuriosityRewardProvider,
)
from mlagents.trainers.torch_entities.components.reward_providers.gail_reward_provider import (
GAILRewardProvider,
)
from mlagents.trainers.torch_entities.components.reward_providers.rnd_reward_provider import (
RNDRewardProvider,
)
from mlagents_envs.base_env import BehaviorSpec
NAME_TO_CLASS: Dict[RewardSignalType, Type[BaseRewardProvider]] = {
RewardSignalType.EXTRINSIC: ExtrinsicRewardProvider,
RewardSignalType.CURIOSITY: CuriosityRewardProvider,
RewardSignalType.GAIL: GAILRewardProvider,
RewardSignalType.RND: RNDRewardProvider,
}
def create_reward_provider(
name: RewardSignalType, specs: BehaviorSpec, settings: RewardSignalSettings
) -> BaseRewardProvider:
"""
Creates a reward provider class based on the name and config entry provided as a dict.
:param name: The name of the reward signal
:param specs: The BehaviorSpecs of the policy
:param settings: The RewardSignalSettings for that reward signal
:return: The reward signal class instantiated
"""
rcls = NAME_TO_CLASS.get(name)
if not rcls:
raise UnityTrainerException(f"Unknown reward signal type {name}")
class_inst = rcls(specs, settings)
return class_inst
| ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/reward_provider_factory.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/reward_provider_factory.py",
"repo_id": "ml-agents",
"token_count": 589
} | 2,048 |
import numpy as np
def discount_rewards(r, gamma=0.99, value_next=0.0):
"""
Computes discounted sum of future rewards for use in updating value estimate.
:param r: List of rewards.
:param gamma: Discount factor.
:param value_next: T+1 value estimate for returns calculation.
:return: discounted sum of future rewards as list.
"""
discounted_r = np.zeros_like(r)
running_add = value_next
for t in reversed(range(0, r.size)):
running_add = running_add * gamma + r[t]
discounted_r[t] = running_add
return discounted_r
def get_gae(rewards, value_estimates, value_next=0.0, gamma=0.99, lambd=0.95):
"""
Computes generalized advantage estimate for use in updating policy.
:param rewards: list of rewards for time-steps t to T.
:param value_next: Value estimate for time-step T+1.
:param value_estimates: list of value estimates for time-steps t to T.
:param gamma: Discount factor.
:param lambd: GAE weighing factor.
:return: list of advantage estimates for time-steps t to T.
"""
value_estimates = np.append(value_estimates, value_next)
delta_t = rewards + gamma * value_estimates[1:] - value_estimates[:-1]
advantage = discount_rewards(r=delta_t, gamma=gamma * lambd)
return advantage
def lambda_return(r, value_estimates, gamma=0.99, lambd=0.8, value_next=0.0):
returns = np.zeros_like(r)
returns[-1] = r[-1] + gamma * value_next
for t in reversed(range(0, r.size - 1)):
returns[t] = (
gamma * lambd * returns[t + 1]
+ r[t]
+ (1 - lambd) * gamma * value_estimates[t + 1]
)
return returns
| ml-agents/ml-agents/mlagents/trainers/trainer/trainer_utils.py/0 | {
"file_path": "ml-agents/ml-agents/mlagents/trainers/trainer/trainer_utils.py",
"repo_id": "ml-agents",
"token_count": 649
} | 2,049 |
import argparse
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.envs.unity_gym_env import UnityToGymWrapper
def test_run_environment(env_name):
"""
Run the gym test using the specified environment
:param env_name: Name of the Unity environment binary to launch
"""
u_env = UnityEnvironment(env_name, worker_id=1, no_graphics=True)
env = UnityToGymWrapper(u_env)
try:
# Examine environment parameters
print(str(env))
# Reset the environment
initial_observations = env.reset()
if len(env.observation_space.shape) == 1:
# Examine the initial vector observation
print(f"Agent observations look like: \n{initial_observations}")
for _episode in range(10):
env.reset()
done = False
episode_rewards = 0
while not done:
actions = env.action_space.sample()
obs, reward, done, _ = env.step(actions)
episode_rewards += reward
print(f"Total reward this episode: {episode_rewards}")
finally:
env.close()
def test_closing(env_name):
"""
Run the gym test and closes the environment multiple times
:param env_name: Name of the Unity environment binary to launch
"""
try:
env1 = UnityToGymWrapper(
UnityEnvironment(env_name, worker_id=1, no_graphics=True)
)
env1.close()
env1 = UnityToGymWrapper(
UnityEnvironment(env_name, worker_id=1, no_graphics=True)
)
env2 = UnityToGymWrapper(
UnityEnvironment(env_name, worker_id=2, no_graphics=True)
)
env2.reset()
finally:
env1.close()
env2.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--env", default="Project/testPlayer")
args = parser.parse_args()
test_run_environment(args.env)
test_closing(args.env)
| ml-agents/ml-agents/tests/yamato/scripts/run_gym.py/0 | {
"file_path": "ml-agents/ml-agents/tests/yamato/scripts/run_gym.py",
"repo_id": "ml-agents",
"token_count": 860
} | 2,050 |
syntax = "proto3";
option csharp_namespace = "Unity.MLAgents.CommunicatorObjects";
package communicator_objects;
message DemonstrationMetaProto {
int32 api_version = 1;
string demonstration_name = 2;
int32 number_steps = 3;
int32 number_episodes = 4;
float mean_reward = 5;
}
| ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/demonstration_meta.proto/0 | {
"file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/demonstration_meta.proto",
"repo_id": "ml-agents",
"token_count": 108
} | 2,051 |
fileFormatVersion: 2
guid: e7f3a5adb034d684cb13cb257c29a1c3
folderAsset: yes
timeCreated: 1504062948
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/Plugins/WebGL.meta/0 | {
"file_path": "xLua/Assets/Plugins/WebGL.meta",
"repo_id": "xLua",
"token_count": 77
} | 2,052 |
fileFormatVersion: 2
guid: 0ae08314c9c889249bbd484254109060
timeCreated: 1529661499
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Doc/Add_Remove_Lua_Lib.md.meta/0 | {
"file_path": "xLua/Assets/XLua/Doc/Add_Remove_Lua_Lib.md.meta",
"repo_id": "xLua",
"token_count": 68
} | 2,053 |
## C# APIs
### LuaEnv type
#### object[] DoString(string chunk, string chunkName = "chuck", LuaTable env = null)
Description:
Executes a code block.
Parameter:
chunk: Lua code string;
chunkName: This is used in the debug message when an error occurs, indicating a certain line in a certain code block has an error.
env: This is the environment variable of this code block.
Returned value:
The returned value of the return statement in the code block.
For example: return 1, "hello". DoString returns an array that will contain two objects. One is 1 of the double type, and the other is the string "hello".
For example:
LuaEnv luaenv = new LuaEnv();
object[] ret = luaenv.DoString("print(‘hello’)\r\nreturn 1")
UnityEngine.Debug.Log("ret="+ret[0]);
luaenv.Dispose()
#### T LoadString<T>(string chunk, string chunkName = "chunk", LuaTable env = null)
Description:
This loads a code block, but does not execute it. It only returns the type can be specified as a delegate or a LuaFunction.
Parameter:
chunk: Lua code string;
chunkName: This is used in the debug message when an error occurs, indicating a certain line in a certain code block has an error.
env: This is the environment variable of this code block.
Returned Value:
This is the delegate or LuaFunction type that represents the code block.
#### LuaTable Global;
Description:
This is the LuaTable representing the Lua global environment.
### void Tick()
Description:
This clears Lua's LuaBase objects that have not been manually released (for example LuaTable, LuaFunction), and other things.
This needs to be called periodically, for example in the Update of MonoBehaviour.
### void AddLoader(CustomLoader loader)
Description:
Adds a custom loader
Parameter:
loader: A delegate that includes the loaded function. The type is delegate byte[] CustomLoader(ref string filepath). When a file is required, the loader will be called back. Its parameters are the parameters used to call require. If the loader finds the file, it reads it into memory and returns a byte array. If debug support is required, the filepath should be set to one the IDE can find (relative or absolute).
#### void Dispose()
Description:
This disposes the LuaEnv.
> LuaEnv usage suggestion: use only one instance globally. Call the GC method in Update, and call Dispose when it is not required.
### LuaTable type
#### T Get<T>(string key)
Description:
Gets the value of type T on key. Null is returned if it does not exist or the type does not match.
#### T GetInPath<T>(string path)
Description:
The difference from Get is that this function will identify the "." in the path. For example, var i = tbl.GetInPath<int>(“a.b.c”) is equivalent to executing i = tbl.abc in Lua. This avoids calling Get multiple times and obtaining intermediate variables. It has higher execution efficiency.
#### void SetInPath<T>(string path, T val)
Description:
Setter corresponding to SetInPath<T>;
#### void Get<TKey, TValue>(TKey key, out TValue value)
Description:
The key of the APIs described above can only be a string, but this API has no such restriction.
#### void Set<TKey, TValue>(TKey key, TValue value)
Description:
This is the setter corresponding to Get<TKey, TValue>.
#### T Cast<T>()
Description:
Converts the table to a type specified by T. It can be an interface with a CSharpCallLua declaration, a type or struct with a default constructor, a Dictionary, a List, and so on.
#### void SetMetaTable(LuaTable metaTable)
Description:
Sets metatable to a table metatable
### LuaFunction type
> Note: Accessing Lua functions with this type will result in overhead from boxing and unboxing. For the sake of performance, do not use this type if frequent calls are required. It is recommended that you use table.Get<ABCDelegate> to get a delegate and then call it (assuming ABCDelegate is a delegate of C#). Before using table.Get<ABCDelegate>, add ABCDelegate to the list of generated code.
#### object[] Call(params object[] args)
Description:
This calls the Lua function with the variable parameters and returns the returned value of the call.
#### object[] Call(object[] args, Type[] returnTypes)
Description:
This calls the Lua function and specifies the type of the returned parameter. The system will automatically convert the specified type.
#### void SetEnv(LuaTable env)
Description:
Equivalent to Lua's setfenv function.
## Lua API
### CS objects
#### CS.namespace.class(...)
Description:
This calls a C# type constructor and returns a type instance.
For Example:
local v1=CS.UnityEngine.Vector3(1,1,1)
#### CS.namespace.class.field
Description:
This accesses a C# static member.
For Example:
Print(CS.UnityEngine.Vector3.one)
#### CS.namespace.enum.field
Description:
This accesses an enumerated value.
#### Typeof Functions
Description:
This is similar to the typeof keyword in C#: a Type object is returned. For example, in GameObject.AddComponent, one overload requires a Type parameter.
For Example:
newGameObj:AddComponent(typeof(CS.UnityEngine.ParticleSystem))
#### Unsigned 64-bit is supported
##### uint64.tostring
Description:
Unsigned number to string.
##### uint64.divide
Description:
Unsigned number division.
##### uint64.compare
Description:
Unsigned comparison: 0 is returned for equal, positive for greater than, and negative for less than.
##### uint64.remainder
Description:
Unsigned modulus.
##### uint64.parse
Description:
String to unsigned number.
#### xlua.structclone
Description:
This clones a c# structure.
#### xlua.private_accessible(class)
Description:
This makes the private fields, properties, methods of a type available.
#### Cast Function
Description:
This indicates that the object is accessed with a specific interface, which is useful when the implementation type is inaccessible (such as internal modification). Use it in the following way (assuming that the following calc object implements C#'s PerformentTest.ICalc interface):
For Example:
cast(calc, typeof(CS.PerformentTest.ICalc))
Then, no other APIs are available.
Accessing a csharp object is like accessing a table. Calling a function is like calling the Lua function. Operators can also be used to access the C# operator. Here is an example:
local v1=CS.UnityEngine.Vector3(1,1,1)
local v2=CS.UnityEngine.Vector3(1,1,1)
v1.x = 100
v2.y = 100
print(v1, v2)
local v3 = v1 + v2
print(v1.x, v2.x)
print(CS.UnityEngine.Vector3.one)
print(CS.UnityEngine.Vector3.Distance(v1, v2))
## Type mapping
### Basic data type
|C# type|Lua type|
|-|-|
|sbyte, byte, short, ushort, int ,uint ,double ,char ,float|number|
|decimal|userdata|
|long ,ulong|userdata/lua_Integer(lua53)|
|bytes[]|string|
|bool|boolean|
|string|string|
### Complex data type
|C# type|Lua type|
|-|-|
|LuaTable|table|
|LuaFunction|function|
|class or struct instance|userdata, table|
|method, delegate|function|
#### LuaTable:
If C# specifies inputting the LuaTable type (including the input parameters of the C# method or the returned value of the Lua method) from Lua, then it must be a table in Lua. Or, if C# does not specify the type, the table in Lua should be converted to LuaTable .
#### LuaFunction:
If C# specifies inputting the LuaFunction type (including the input parameters of the C# method or the returned value of the Lua method) from Lua, then it must be a function in Lua. Or, if C# does not specify the type, the function on Lua should be converted to LuaFunction.
#### LuaUserData:
This is Lua userdata corresponding to the non-C# Managered object.
#### Class or struct instance:
This transfers a class or struct instance from C#, maps it to Lua userdata, and accesses the member of the userdata via __index.
If C# specifies inputting objects of the specified type from Lua, then the userdata of the type instance is used directly in Lua. If the specified type has a default constructor, the table in Lua is automatically converted. The conversion rule is: call the constructor to construct an instance, and convert the field corresponding to table to each setter member in C#.
#### Method and delegate:
Both member methods and delegates correspond to the Lua functions.
The ordinary parameters and reference parameters on C# correspond to the Lua function parameters. The returned value on C# corresponds to the first returned value on Lua. The reference parameters and out parameters correspond to the 2nd to Nth parameters on Lua in sequence.
## Macros
#### HOTFIX_ENABLE
This enables the hotfix function.
#### NOT_GEN_WARNING
This prints warning when there is reflection.
#### GEN_CODE_MINIMIZE
Generates code in a way that minimizes the code segments.
| xLua/Assets/XLua/Doc/XLua_API_EN.md/0 | {
"file_path": "xLua/Assets/XLua/Doc/XLua_API_EN.md",
"repo_id": "xLua",
"token_count": 2526
} | 2,054 |
## 使用方式
1、打开该特性
添加HOTFIX_ENABLE宏,(在Unity3D的File->Build Setting->Scripting Define Symbols下添加)。编辑器、各手机平台这个宏要分别设置!如果是自动化打包,要注意在代码里头用API设置的宏是不生效的,需要在编辑器设置。
(建议平时开发业务代码不打开HOTFIX_ENABLE,只在build手机版本或者要在编译器下开发补丁时打开HOTFIX_ENABLE)
2、执行XLua/Generate Code菜单。
3、注入,构建手机包这个步骤会在构建时自动进行,编辑器下开发补丁需要手动执行"XLua/Hotfix Inject In Editor"菜单。打印“hotfix inject finish!”或者“had injected!”才算成功,否则会打印错误信息。
如果已经打印了“hotfix inject finish!”或者“had injected!”,执行xlua.hotfix仍然报类似“xlua.access, no field __Hitfix0_Update”的错误,要么是该类没配置到Hotfix列表,要么是注入成功后,又触发了编译,覆盖了注入结果。
## 约束
不支持静态构造函数。
目前只支持Assets下代码的热补丁,不支持引擎,c#系统库的热补丁。
## API
xlua.hotfix(class, [method_name], fix)
* 描述 : 注入lua补丁
* class : C#类,两种表示方法,CS.Namespace.TypeName或者字符串方式"Namespace.TypeName",字符串格式和C#的Type.GetType要求一致,如果是内嵌类型(Nested Type)是非Public类型的话,只能用字符串方式表示"Namespace.TypeName+NestedTypeName";
* method_name : 方法名,可选;
* fix : 如果传了method_name,fix将会是一个function,否则通过table提供一组函数。table的组织按key是method_name,value是function的方式。
base(csobj)
* 描述 : 子类override函数通过base调用父类实现。
* csobj : 对象
* 返回值 : 新对象,可以通过该对象base上的方法
例子(位于HotfixTest2.cs):
```lua
xlua.hotfix(CS.BaseTest, 'Foo', function(self, p)
print('BaseTest', p)
base(self):Foo(p)
end)
```
util.hotfix_ex(class, method_name, fix)
* 描述 : xlua.hotfix的增强版本,可以在fix函数里头执行原来的函数,缺点是fix的执行会略慢。
* method_name : 方法名;
* fix : 用来替换C#方法的lua function。
## 标识要热更新的类型
和其它配置一样,有两种方式
方式一:直接在类里头打Hotfix标签(不建议,示例只是为了方便演示采取这种方式);
!!注意,方式一在高版本unity不支持
方式二:在一个static类的static字段或者属性里头配置一个列表。属性可以用于实现的比较复杂的配置,比如根据Namespace做白名单。
!!注意,高版本Unity需要把配置文件放Editor目录下
~~~csharp
//如果涉及到Assembly-CSharp.dll之外的其它dll,如下代码需要放到Editor目录
public static class HotfixCfg
{
[Hotfix]
public static List<Type> by_field = new List<Type>()
{
typeof(HotFixSubClass),
typeof(GenericClass<>),
};
[Hotfix]
public static List<Type> by_property
{
get
{
return (from type in Assembly.Load("Assembly-CSharp").GetTypes()
where type.Namespace == "XXXX"
select type).ToList();
}
}
}
~~~
## Hotfix Flag
Hotfix标签可以设置一些标志位对生成代码及插桩定制化
* Stateless、Stateful
遗留设置,Stateful方式在新版本已经删除,因为这种方式可以用xlua.util.state接口达到类似的效果,该接口的使用可以看下HotfixTest2.cs里的示例代码。
由于没Stateful,默认就是Stateless,所以也没必要设置该标志位。
* ValueTypeBoxing
值类型的适配delegate会收敛到object,好处是代码量更少,不好的是值类型会产生boxing及gc,适用于对text段敏感的业务。
* IgnoreProperty
不对属性注入及生成适配代码,一般而言,大多数属性的实现都很简单,出错几率比较小,建议不注入。
* IgnoreNotPublic
不对非public的方法注入及生成适配代码。除了像MonoBehaviour那种会被反射调用的私有方法必须得注入,其它仅被本类调用的非public方法可以不注入,只不过修复时会工作量稍大,所有引用到这个函数的public方法都要重写。
* Inline
不生成适配delegate,直接在函数体注入处理代码。
* IntKey
不生成静态字段,而是把所有注入点放到一个数组集中管理。
好处:对text段影响小。
坏处:使用不像默认方式那么方便,需要通过id来指明hotfix哪个函数,而这个id是代码注入工具时分配的,函数到id的映射会保存在Gen/Resources/hotfix_id_map.lua.txt,并且自动加时间戳备份到hotfix_id_map.lua.txt同级目录,发布手机版本后请妥善保存该文件。
该文件的格式大概如下(注意:该文件仅IntKey模式使用,当你没类型指定IntKey模式注入,该文件只返回个空表):
~~~lua
return {
["HotfixTest"] = {
[".ctor"] = {
5
},
["Start"] = {
6
},
["Update"] = {
7
},
["FixedUpdate"] = {
8
},
["Add"] = {
9,10
},
["OnGUI"] = {
11
},
},
}
~~~
想要替换HotfixTest的Update函数,你得
~~~lua
CS.XLua.HotfixDelegateBridge.Set(7, func)
~~~
如果是重载函数,将会一个函数名对应多个id,比如上面的Add函数。
能不能自动化一些呢?可以,xlua.util提供了auto_id_map函数,执行一次后你就可以像以前那样直接用类,方法名去指明修补的函数。
~~~lua
(require 'xlua.util').auto_id_map()
xlua.hotfix(CS.HotfixTest, 'Update', function(self)
self.tick = self.tick + 1
if (self.tick % 50) == 0 then
print('<<<<<<<<Update in lua, tick = ' .. self.tick)
end
end)
~~~
前提是hotfix_id_map.lua.txt放到可以通过require 'hotfix_id_map'引用到的地方。
## 使用建议
* 对所有较大可能变动的类型加上Hotfix标识;
* 建议用反射找出所有函数参数、字段、属性、事件涉及的delegate类型,标注CSharpCallLua;
* 业务代码、引擎API、系统API,需要在Lua补丁里头高性能访问的类型,加上LuaCallCSharp;
* 引擎API、系统API可能被代码剪裁调(C#无引用的地方都会被剪裁),如果觉得可能会新增C#代码之外的API调用,这些API所在的类型要么加LuaCallCSharp,要么加ReflectionUse;
## 打补丁
xlua可以用lua函数替换C#的构造函数,函数,属性,事件的替换。lua实现都是函数,比如属性对于一个getter函数和一个setter函数,事件对应一个add函数和一个remove函数。
* 函数
method_name传函数名,支持重载,不同重载都是转发到同一个lua函数。
比如:
```csharp
// 要fix的C#类
[Hotfix]
public class HotfixCalc
{
public int Add(int a, int b)
{
return a - b;
}
public Vector3 Add(Vector3 a, Vector3 b)
{
return a - b;
}
}
```
```lua
xlua.hotfix(CS.HotfixCalc, 'Add', function(self, a, b)
return a + b
end)
```
静态函数和成员函数的区别是,成员函数会加一个self参数,这个self在Stateless方式下是C#对象本身(对应C#的this)
普通参数对于lua的参数,ref参数对应lua的一个参数和一个返回值,out参数对于lua的一个返回值。
泛化函数的打补丁规则和普通函数一样。
* 构造函数
构造函数对应的method_name是".ctor"。
和普通函数不一样的是,构造函数的热补丁并不是替换,而是执行原有逻辑后调用lua。
* 属性
对于名为“AProp”的属性,会对应一个getter,method_name等于get_AProp,setter的method_name等于set_AProp。
* []操作符
赋值对应set_Item,取值对应get_Item。第一个参数是self,赋值后面跟key,value,取值只有key参数,返回值是取出的值。
* 其它操作符
C#的操作符都有一套内部表示,比如+号的操作符函数名是op_Addition(其它操作符的内部表示可以去请参照相关资料),覆盖这函数就覆盖了C#的+号操作符。
* 事件
比如对于事件“AEvent”,+=操作符是add_AEvent,-=对应的是remove_AEvent。这两个函数均是第一个参数是self,第二个参数是操作符后面跟的delegate。
通过xlua.private_accessible(版本号大于2.1.11不需要调用xlua.private_accessible)来直接访问事件对应的私有delegate的直接访问后,可以通过对象的"&事件名"字段直接触发事件,例如self\['&MyEvent'\](),其中MyEvent是事件名。
* 析构函数
method_name是"Finalize",传一个self参数。
和普通函数不一样的是,析构函数的热补丁并不是替换,而是开头调用lua函数后继续原有逻辑。
* 泛化类型
其它规则一致,需要说明的是,每个泛化类型实例化后都是一个独立的类型,只能针对实例化后的类型分别打补丁。比如:
```csharp
public class GenericClass<T>
{
}
```
你只能对GenericClass\<double\>,GenericClass\<int\>这些类,而不是对GenericClass打补丁。
对GenericClass<double>打补丁的实例如下:
```csharp
luaenv.DoString(@"
xlua.hotfix(CS.GenericClass(CS.System.Double), {
['.ctor'] = function(obj, a)
print('GenericClass<double>', obj, a)
end;
Func1 = function(obj)
print('GenericClass<double>.Func1', obj)
end;
Func2 = function(obj)
print('GenericClass<double>.Func2', obj)
return 1314
end
})
");
```
* Unity协程
通过util.cs_generator可以用一个function模拟一个IEnumerator,在里头用coroutine.yield,就类似C#里头的yield return。比如下面的C#代码和对应的hotfix代码是等同效果的
~~~csharp
[XLua.Hotfix]
public class HotFixSubClass : MonoBehaviour {
IEnumerator Start()
{
while (true)
{
yield return new WaitForSeconds(3);
Debug.Log("Wait for 3 seconds");
}
}
}
~~~
~~~csharp
luaenv.DoString(@"
local util = require 'xlua.util'
xlua.hotfix(CS.HotFixSubClass,{
Start = function(self)
return util.cs_generator(function()
while true do
coroutine.yield(CS.UnityEngine.WaitForSeconds(3))
print('Wait for 3 seconds')
end
end)
end;
})
");
~~~
* 整个类
如果要替换整个类,不需要一次次的调用xlua.hotfix去替换,可以整个一次完成。只要给一个table,按method_name = function组织即可
```lua
xlua.hotfix(CS.StatefullTest, {
['.ctor'] = function(csobj)
return util.state(csobj, {evt = {}, start = 0, prop = 0})
end;
set_AProp = function(self, v)
print('set_AProp', v)
self.prop = v
end;
get_AProp = function(self)
return self.prop
end;
get_Item = function(self, k)
print('get_Item', k)
return 1024
end;
set_Item = function(self, k, v)
print('set_Item', k, v)
end;
add_AEvent = function(self, cb)
print('add_AEvent', cb)
table.insert(self.evt, cb)
end;
remove_AEvent = function(self, cb)
print('remove_AEvent', cb)
for i, v in ipairs(self.evt) do
if v == cb then
table.remove(self.evt, i)
break
end
end
end;
Start = function(self)
print('Start')
for _, cb in ipairs(self.evt) do
cb(self.start, 2)
end
self.start = self.start + 1
end;
StaticFunc = function(a, b, c)
print(a, b, c)
end;
GenericTest = function(self, a)
print(self, a)
end;
Finalize = function(self)
print('Finalize', self)
end
})
```
| xLua/Assets/XLua/Doc/hotfix.md/0 | {
"file_path": "xLua/Assets/XLua/Doc/hotfix.md",
"repo_id": "xLua",
"token_count": 7355
} | 2,055 |
fileFormatVersion: 2
guid: 2e190b5ef59b7a84dbb262cfd11f9107
timeCreated: 1478591887
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Examples/04_LuaObjectOrented/InvokeLua.cs.meta/0 | {
"file_path": "xLua/Assets/XLua/Examples/04_LuaObjectOrented/InvokeLua.cs.meta",
"repo_id": "xLua",
"token_count": 102
} | 2,056 |
using UnityEngine;
namespace XLuaTest
{
[XLua.Hotfix]
public class StatefullTest
{
public StatefullTest()
{
}
public StatefullTest(int a, int b)
{
if (a > 0)
{
return;
}
Debug.Log("a=" + a);
if (b > 0)
{
return;
}
else
{
if (a + b > 0)
{
return;
}
}
Debug.Log("b=" + b);
}
public int AProp
{
get;
set;
}
public event System.Action<int, double> AEvent;
public int this[string field]
{
get
{
return 1;
}
set
{
}
}
public void Start()
{
}
void Update()
{
}
public void GenericTest<T>(T a)
{
}
static public void StaticFunc(int a, int b)
{
}
static public void StaticFunc(string a, int b, int c)
{
}
~StatefullTest()
{
Debug.Log("~StatefullTest");
}
}
}
| xLua/Assets/XLua/Examples/08_Hotfix/StatefullTest.cs/0 | {
"file_path": "xLua/Assets/XLua/Examples/08_Hotfix/StatefullTest.cs",
"repo_id": "xLua",
"token_count": 839
} | 2,057 |
fileFormatVersion: 2
guid: 25beaf0816ae33a43b715f68010bbfdd
timeCreated: 1489377018
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Examples/10_SignatureLoader/Resources/signatured3.lua.bytes.meta/0 | {
"file_path": "xLua/Assets/XLua/Examples/10_SignatureLoader/Resources/signatured3.lua.bytes.meta",
"repo_id": "xLua",
"token_count": 70
} | 2,058 |
fileFormatVersion: 2
guid: 7ea057dec6022624fa54a0ccc12648ee
folderAsset: yes
timeCreated: 1531790017
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Examples/13_BuildFromCLI.meta/0 | {
"file_path": "xLua/Assets/XLua/Examples/13_BuildFromCLI.meta",
"repo_id": "xLua",
"token_count": 79
} | 2,059 |
fileFormatVersion: 2
guid: 9e05f05f4a331bc45a04832062650a9e
timeCreated: 1458812943
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Resources/tdr/tdr.lua.txt.meta/0 | {
"file_path": "xLua/Assets/XLua/Resources/tdr/tdr.lua.txt.meta",
"repo_id": "xLua",
"token_count": 71
} | 2,060 |
fileFormatVersion: 2
guid: 9f94464b9267f9b4cbf2f98681e22880
folderAsset: yes
timeCreated: 1479105499
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Src/Editor/LinkXmlGen.meta/0 | {
"file_path": "xLua/Assets/XLua/Src/Editor/LinkXmlGen.meta",
"repo_id": "xLua",
"token_count": 78
} | 2,061 |
using UnityEngine;
using System.Collections;
namespace XLua
{
public class TemplateRef : ScriptableObject
{
public TextAsset LuaClassWrap;
public TextAsset LuaClassWrapGCM;
public TextAsset LuaDelegateBridge;
public TextAsset LuaDelegateWrap;
public TextAsset LuaEnumWrap;
public TextAsset LuaEnumWrapGCM;
public TextAsset LuaInterfaceBridge;
public TextAsset LuaRegister;
public TextAsset LuaRegisterGCM;
public TextAsset LuaWrapPusher;
public TextAsset PackUnpack;
public TextAsset TemplateCommon;
}
}
| xLua/Assets/XLua/Src/Editor/TemplateRef.cs/0 | {
"file_path": "xLua/Assets/XLua/Src/Editor/TemplateRef.cs",
"repo_id": "xLua",
"token_count": 240
} | 2,062 |
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
namespace XLua
{
public partial class LuaFunction : LuaBase
{
public LuaFunction(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
//Action和Func是方便使用的无gc api,如果需要用到out,ref参数,建议使用delegate
//如果需要其它个数的Action和Func, 这个类声明为partial,可以自己加
public void Action<T>(T a)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a);
int error = LuaAPI.lua_pcall(L, 1, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T, TResult>(T a)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a);
int error = LuaAPI.lua_pcall(L, 1, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try
{
translator.Get(L, -1, out ret);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1, T2>(T1 a1, T2 a2)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a1);
translator.PushByType(L, a2);
int error = LuaAPI.lua_pcall(L, 2, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, T2, TResult>(T1 a1, T2 a2)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a1);
translator.PushByType(L, a2);
int error = LuaAPI.lua_pcall(L, 2, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try
{
translator.Get(L, -1, out ret);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//deprecated
public object[] Call(object[] args, Type[] returnTypes)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
int nArgs = 0;
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
if (args != null)
{
nArgs = args.Length;
for (int i = 0; i < args.Length; i++)
{
translator.PushAny(L, args[i]);
}
}
int error = LuaAPI.lua_pcall(L, nArgs, -1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_remove(L, errFunc);
if (returnTypes != null)
return translator.popValues(L, oldTop, returnTypes);
else
return translator.popValues(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//deprecated
public object[] Call(params object[] args)
{
return Call(args, null);
}
public T Cast<T>()
{
if (!typeof(T).IsSubclassOf(typeof(Delegate)))
{
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
}
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
push(L);
T ret = (T)translator.GetObject(L, -1, typeof(T));
LuaAPI.lua_pop(luaEnv.L, 1);
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void SetEnv(LuaTable env)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
push(L);
env.push(L);
LuaAPI.lua_setfenv(L, -2);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
internal override void push(RealStatePtr L)
{
LuaAPI.lua_getref(L, luaReference);
}
public override string ToString()
{
return "function :" + luaReference;
}
}
}
| xLua/Assets/XLua/Src/LuaFunction.cs/0 | {
"file_path": "xLua/Assets/XLua/Src/LuaFunction.cs",
"repo_id": "xLua",
"token_count": 4322
} | 2,063 |
#if !UNITY_WSA || UNITY_EDITOR
using System.Security.Cryptography;
#else
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
#endif
using System;
namespace XLua
{
public class SignatureLoader
{
private LuaEnv.CustomLoader userLoader;
#if !UNITY_WSA || UNITY_EDITOR
RSACryptoServiceProvider rsa;
SHA1 sha;
#else
AsymmetricKeyAlgorithmProvider rsa;
CryptographicKey key;
#endif
public SignatureLoader(string publicKey, LuaEnv.CustomLoader loader)
{
#if !UNITY_WSA || UNITY_EDITOR
rsa = new RSACryptoServiceProvider();
rsa.ImportCspBlob(Convert.FromBase64String(publicKey));
sha = new SHA1CryptoServiceProvider();
#else
rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
key = rsa.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
#endif
userLoader = loader;
}
byte[] load_and_verify(ref string filepath)
{
byte[] data = userLoader(ref filepath);
if (data == null)
{
return null;
}
if (data.Length < 128)
{
throw new InvalidProgramException(filepath + " length less than 128!");
}
byte[] sig = new byte[128];
byte[] filecontent = new byte[data.Length - 128];
Array.Copy(data, sig, 128);
Array.Copy(data, 128, filecontent, 0, filecontent.Length);
#if !UNITY_WSA || UNITY_EDITOR
if (!rsa.VerifyData(filecontent, sha, sig))
{
throw new InvalidProgramException(filepath + " has invalid signature!");
}
#else
if (!CryptographicEngine.VerifySignature(key, CryptographicBuffer.CreateFromByteArray(filecontent), CryptographicBuffer.CreateFromByteArray(sig)))
{
throw new InvalidProgramException(filepath + " has invalid signature!");
}
#endif
return filecontent;
}
public static implicit operator LuaEnv.CustomLoader(SignatureLoader signatureLoader)
{
return signatureLoader.load_and_verify;
}
}
} | xLua/Assets/XLua/Src/SignatureLoader.cs/0 | {
"file_path": "xLua/Assets/XLua/Src/SignatureLoader.cs",
"repo_id": "xLua",
"token_count": 1037
} | 2,064 |
fileFormatVersion: 2
guid: 0b0cb24da8f1e8746b57219f9cb3d794
timeCreated: 1455872284
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Assets/XLua/Tutorial/CSharpCallLua/CSCallLua.unity.meta/0 | {
"file_path": "xLua/Assets/XLua/Tutorial/CSharpCallLua/CSCallLua.unity.meta",
"repo_id": "xLua",
"token_count": 73
} | 2,065 |
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using UnityEngine;
using System.Collections;
using XLua;
namespace Tutorial
{
public class CustomLoader : MonoBehaviour
{
LuaEnv luaenv = null;
// Use this for initialization
void Start()
{
luaenv = new LuaEnv();
luaenv.AddLoader((ref string filename) =>
{
if (filename == "InMemory")
{
string script = "return {ccc = 9999}";
return System.Text.Encoding.UTF8.GetBytes(script);
}
return null;
});
luaenv.DoString("print('InMemory.ccc=', require('InMemory').ccc)");
}
// Update is called once per frame
void Update()
{
if (luaenv != null)
{
luaenv.Tick();
}
}
void OnDestroy()
{
luaenv.Dispose();
}
}
}
| xLua/Assets/XLua/Tutorial/LoadLuaScript/Loader/CustomLoader.cs/0 | {
"file_path": "xLua/Assets/XLua/Tutorial/LoadLuaScript/Loader/CustomLoader.cs",
"repo_id": "xLua",
"token_count": 678
} | 2,066 |
using System;
using System.IO;
using System.Security.Cryptography;
namespace XLua
{
public class KeyPairsGen
{
public static void Main(string[] args)
{
if (File.Exists("key_ras") || File.Exists("key_ras.pub"))
{
Console.WriteLine("key pairs existed!");
}
var rsa = new RSACryptoServiceProvider();
File.WriteAllText("key_ras", rsa.ToXmlString(true));
File.WriteAllText("key_ras.pub", Convert.ToBase64String(rsa.ExportCspBlob(false)));
}
}
} | xLua/General/Src/KeyPairsGen.cs/0 | {
"file_path": "xLua/General/Src/KeyPairsGen.cs",
"repo_id": "xLua",
"token_count": 278
} | 2,067 |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{54C2A82C-C04D-16F1-C95E-99E5356972F1}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>XLuaTestGenCode</RootNamespace>
<AssemblyName>XLuaTestGenCode</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Bin\</OutputPath>
<BaseIntermediateOutputPath>obj\Any CPU\Debug\XLuaTestGenCode\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath>
<DefineConstants>_DEBUG;DEBUG;TRACE;;XLUA_GENERAL;HOTFIX_ENABLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Bin\</OutputPath>
<BaseIntermediateOutputPath>obj\Any CPU\Release\XLuaTestGenCode\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath>
<DefineConstants>;XLUA_GENERAL;HOTFIX_ENABLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Assets\XLua\Src\CodeEmit.cs">
<Link>Assets\XLua\Src\CodeEmit.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\CopyByValue.cs">
<Link>Assets\XLua\Src\CopyByValue.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\DelegateBridge.cs">
<Link>Assets\XLua\Src\DelegateBridge.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\GenAttributes.cs">
<Link>Assets\XLua\Src\GenAttributes.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\GenericDelegateBridge.cs">
<Link>Assets\XLua\Src\GenericDelegateBridge.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\InternalGlobals.cs">
<Link>Assets\XLua\Src\InternalGlobals.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaBase.cs">
<Link>Assets\XLua\Src\LuaBase.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaDLL.cs">
<Link>Assets\XLua\Src\LuaDLL.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaEnv.cs">
<Link>Assets\XLua\Src\LuaEnv.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaException.cs">
<Link>Assets\XLua\Src\LuaException.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaFunction.cs">
<Link>Assets\XLua\Src\LuaFunction.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\LuaTable.cs">
<Link>Assets\XLua\Src\LuaTable.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\MethodWarpsCache.cs">
<Link>Assets\XLua\Src\MethodWarpsCache.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\ObjectCasters.cs">
<Link>Assets\XLua\Src\ObjectCasters.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\ObjectPool.cs">
<Link>Assets\XLua\Src\ObjectPool.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\ObjectTranslator.cs">
<Link>Assets\XLua\Src\ObjectTranslator.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\ObjectTranslatorPool.cs">
<Link>Assets\XLua\Src\ObjectTranslatorPool.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\RawObject.cs">
<Link>Assets\XLua\Src\RawObject.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\SignatureLoader.cs">
<Link>Assets\XLua\Src\SignatureLoader.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\StaticLuaCallbacks.cs">
<Link>Assets\XLua\Src\StaticLuaCallbacks.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\TemplateEngine\TemplateEngine.cs">
<Link>Assets\XLua\Src\TemplateEngine\TemplateEngine.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\TypeExtensions.cs">
<Link>Assets\XLua\Src\TypeExtensions.cs</Link>
</Compile>
<Compile Include="..\..\Assets\XLua\Src\Utils.cs">
<Link>Assets\XLua\Src\Utils.cs</Link>
</Compile>
<Compile Include="..\Gen1\AccessByGenGodeWrap.cs">
<Link>Gen1\AccessByGenGodeWrap.cs</Link>
</Compile>
<Compile Include="..\Gen1\CalcWrap.cs">
<Link>Gen1\CalcWrap.cs</Link>
</Compile>
<Compile Include="..\Gen1\DelegatesGensBridge.cs">
<Link>Gen1\DelegatesGensBridge.cs</Link>
</Compile>
<Compile Include="..\Gen1\EnumWrap.cs">
<Link>Gen1\EnumWrap.cs</Link>
</Compile>
<Compile Include="..\Gen1\PackUnpack.cs">
<Link>Gen1\PackUnpack.cs</Link>
</Compile>
<Compile Include="..\Gen1\PointWrap.cs">
<Link>Gen1\PointWrap.cs</Link>
</Compile>
<Compile Include="..\Gen1\WrapPusher.cs">
<Link>Gen1\WrapPusher.cs</Link>
</Compile>
<Compile Include="..\Gen1\XLuaGenAutoRegister.cs">
<Link>Gen1\XLuaGenAutoRegister.cs</Link>
</Compile>
<Compile Include="..\Src\XLuaTest.cs">
<Link>Src\XLuaTest.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | xLua/General/vs2013/XLuaTestGenCode.csproj/0 | {
"file_path": "xLua/General/vs2013/XLuaTestGenCode.csproj",
"repo_id": "xLua",
"token_count": 2776
} | 2,068 |
fileFormatVersion: 2
guid: af3706b030ae190448b7feef19dbe395
timeCreated: 1483528414
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Test/UnitTest/StreamingAssets/D.lua.meta/0 | {
"file_path": "xLua/Test/UnitTest/StreamingAssets/D.lua.meta",
"repo_id": "xLua",
"token_count": 67
} | 2,069 |
require("ltest.init")
require "libtdrlua"
pkg_table = {
head = {
magic = 0x7FFF,
msgid = 10000001,
cmd = 1,
version = 0,
bodyLen = 0,
datetime = libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"),
srcIp = libtdrlua.str2tdrip("127.0.0.1"),
},
body = {
login = {
name = "FrancisHe",
pass = "123456",
zone = "Japan",
destIp = libtdrlua.str2tdrip("127.0.0.1"),
},
logout = {
reason = -1,
count = 2,
attr = {-1, 0, 1},
},
xxx = {
typeTester = {
date = libtdrlua.str2tdrdate("2015-09-08"),
time = libtdrlua.str2tdrtime("22:17:59"),
int8 = -1,
uint8Array = {0, 23, 255},
int8VarArrayRefer = 2,
int8VarArray = {-128, 127 ,0},
int = -6, -- -6.6
uintArray = {0, 1721, 0xFFFFFFFF},
intVarArrayRefer = 1, -- 0
intVarArray = {-0x80000000, 0x7FFFFFFF, 0},
strArray = {"Francis", "Francis"},
uint64 = 0xFFFFFFFFFFFFF, -- 1(s) + 11(e) + 52(m)
int64Array = {-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},
float = 0xFFFFFFFF,
floatArray = {-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}, -- 3.40282347e+38
double = 2.2250738585072014e-308,
doubleArray = {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308},
},
boundary = -1.1,
selector = 1,
innerUnion = {
field1 = {
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0,
}
}
},
structArray = {
count = 1, -- 0
array = {
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
}
},
boundary2 = 1.111111,
},
ext1 = -1,
ext2 = {0, 1, 2},
ext3 = {"Francis", "Francis"},
ext4 = "Francis",
}
}
pkg_table_v4 = {
head = {
magic = 0x7FFF,
msgid = 10000001,
cmd = 1,
version = 0,
bodyLen = 0,
datetime = libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"),
srcIp = libtdrlua.str2tdrip("127.0.0.1"),
destIp = libtdrlua.str2tdrip("127.0.0.2"),
},
body = {
login = {
name = "FrancisHe",
pass = "123456",
zone = "Japan",
destIp = libtdrlua.str2tdrip("127.0.0.1"),
},
logout = {
reason = -1,
count = 2,
attr = {-1, 0, 1},
},
xxx = {
typeTester = {
date = libtdrlua.str2tdrdate("2015-09-08"),
time = libtdrlua.str2tdrtime("22:17:59"),
int8 = -1,
uint8Array = {0, 23, 255},
int8VarArrayRefer = 2,
int8VarArray = {-128, 127 ,0},
int = -6, -- -6.6
uintArray = {0, 1721, 0xFFFFFFFF},
intVarArrayRefer = 1, -- 0
intVarArray = {-0x80000000, 0x7FFFFFFF, 0},
strArray = {"Francis", "Francis"},
uint64 = 0xFFFFFFFFFFFFF, -- 1(s) + 11(e) + 52(m)
int64Array = {-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},
float = 0xFFFFFFFF,
floatArray = {-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}, -- 3.40282347e+38
double = 2.2250738585072014e-308,
doubleArray = {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308},
},
boundary = -1.1,
selector = 1,
innerUnion = {
field1 = {
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0,
}
}
},
structArray = {
count = 1, -- 0
array = {
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
{
uint64 = 0x0FFFFFFFFFFFFFFF,
uint = 0xFFFFFFFF,
},
}
},
boundary2 = 1.111111,
},
ext1 = -1,
ext2 = {0, 1, 2},
ext3 = {"Francis", "Francis"},
ext4 = "Francis",
}
}
function copyTab(st)
local tab = {}
for k, v in pairs(st or {}) do
if type(v) ~= "table" then
tab[k] = v
else
tab[k] = copyTab(v)
end
end
return tab
end
local function table_to_string(t)
local ret = ''
local ltype = type(t)
if (ltype == 'table') then
ret = ret .. '{ '
for key,value in pairs(t) do
ret = ret .. tostring(key) .. '=' .. table_to_string(value) .. ' '
end
ret = ret .. '}'
elseif ltype == 'string' then
ret = ret .. "'" .. tostring(t) .. "'"
else
ret = ret .. tostring(t)
end
return ret
end
-- for test case
CMyTestCaseLuaTdr = TestCase:new()
function CMyTestCaseLuaTdr:new(oo)
local o = oo or {}
o.count = 1
setmetatable(o, self)
self.__index = self
return o
end
function CMyTestCaseLuaTdr.SetUpTestCase(self)
self.count = 1 + self.count
print("CMyTestCaseLuaTdr.SetUpTestCase")
end
function CMyTestCaseLuaTdr.TearDownTestCase(self)
self.count = 1 + self.count
print("CMyTestCaseLuaTdr.TearDownTestCase")
end
function CMyTestCaseLuaTdr.SetUp(self)
self.count = 1 + self.count
print("CMyTestCaseLuaTdr.SetUp")
end
function CMyTestCaseLuaTdr.TearDown(self)
self.count = 1 + self.count
print("CMyTestCaseLuaTdr.TearDown")
end
function CMyTestCaseLuaTdr.LoadMetalib(self, load_type, file_path, cmd)
--加载meta元数据库
local ret_code, metalib
if load_type == 0 then
ret_code, metalib = libtdrlua.load_metalib(file_path)
if ret_code ~= 0 then
print("libtdrlua.load_metalib() failed: " .. metalib)
end
end
if load_type == 1 then
local tdrmeta = CS.UnityEngine.Resources.Load(file_path).bytes
ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
if ret_code ~= 0 then
print("libtdrlua.load_metalib_buf() failed: " .. metalib)
end
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.load_metalib ok")
--获取最大meta buff size
local ret_code, buf_size = libtdrlua.metamaxbufsize(metalib, "Pkg")
if ret_code ~= 0 then
print("libtdrlua.metamaxbufsize() failed: " .. buf_size)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.metamaxbufsize() ok: buf_size = " .. buf_size)
--分配buff
local ret_code, buf = libtdrlua.bufalloc(buf_size)
if ret_code ~= 0 then
print("libtdrlua.bufalloc() failed: " .. buf)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.bufalloc() ok")
print( "pkg = " .. table_to_string(pkg_table))
------------------------------------------------------------------------
-- API - get_meta
-- return value - ret_code, meta/err_msg
----------------------------------------------------------------------
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
if ret_code ~= 0 then
print("libtdrlua.get_meta() failed: " .. meta)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.get_meta() ok")
pkg_table.head.cmd = cmd
----------------------------------------------------------------------
-- API - table2buf
-- return value - ret_code, used_size/err_msg
----------------------------------------------------------------------
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
if ret_code ~= 0 then
print("libtdrlua.table2buf() failed: " .. used_size)
libtdrlua.buffree(buf)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.table2buf() ok, used_size = " .. used_size)
----------------------------------------------------------------------
-- API - buf2str
-- return value - ret_code, str/err_msg
----------------------------------------------------------------------
local ret_code, str = libtdrlua.buf2str(buf, used_size)
if ret_code ~= 0 then
print("libtdrlua.buf2str() failed: " .. str)
libtdrlua.buffree(buf)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.buf2str() ok")
print("buf2str:" .. str)
----------------------------------------------------------------------
-- API - buf2table
-- return value - ret_code, pkg_table, used_size/err_msg
----------------------------------------------------------------------
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size, 0)
if ret_code ~= 0 then
print("libtdrlua.buf2table() failed: " .. used_size2)
print(DataDumper(pkg_table2, "pkg2 = "))
libtdrlua.buffree(buf)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.buf2table() ok, used_size = " .. used_size2)
print("unpakc pkg = ", table_to_string(pkg_table2))
--print(DataDumper(pkg_table2, "pkg2 = "))
--因为str为空,所以会引起Unity crash
----------------------------------------------------------------------
-- API - str2table
-- return value - ret_code, pkg_table, used_size/err_msg
----------------------------------------------------------------------
local ret_code, pkg_table3, used_size3 = libtdrlua.str2table(meta, str, 0)
if ret_code ~= 0 then
print("libtdrlua.str2table() failed: " .. used_size3)
print(DataDumper(pkg_table3, "pkg3 = "))
libtdrlua.buffree(buf)
end
ASSERT_EQ(ret_code, 0)
print("libtdrlua.str2table() ok, used_size = " .. used_size3)
print("str2buf unpack pkg = ", table_to_string(pkg_table2))
----------------------------------------------------------------------
-- API - buffree
-- return value - nil/err_msg
----------------------------------------------------------------------
local err_msg = libtdrlua.buffree(buf)
if err_msg ~= nil then
print("libtdrlua.buffree() failed: " .. err_msg)
end
print("libtdrlua.buffree() ok")
ASSERT_EQ(err_msg, nil)
----------------------------------------------------------------------
-- API - free_metalib
-- return value - nil/err_msg
-- Note: metalib will be automatically released by lua gc. Thus, this
-- step is optional.
----------------------------------------------------------------------
local err_msg = libtdrlua.free_metalib(metalib)
if err_msg ~= nil then
print("libtdrlua.free_metalib() failed: " .. err_msg)
end
print("libtdrlua.free_metalib() ok")
ASSERT_EQ(err_msg, nil)
return pkg_table2, pkg_table3
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_1(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2, pkg_table3 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 1)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
--ASSERT_EQ(tostring(pkg_table2.head.bodyLen),"39")
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 1)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 39)
--ASSERT_EQ(tostring(pkg_table3.head.bodyLen),"39")
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table3.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table3.body.login.pass, "123456")
ASSERT_EQ(pkg_table3.body.login.zone, "Japan")
ASSERT_EQ(pkg_table3.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.ext1, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_1(self)
self.count = 1 + self.count
pkg_table2, pkg_table3 = self:LoadMetalib(1, "testxxx.tdr", 1)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 1)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 39)
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table3.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table3.body.login.pass, "123456")
ASSERT_EQ(pkg_table3.body.login.zone, "Japan")
ASSERT_EQ(pkg_table3.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.ext1, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_2(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2, pkg_table3 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 2)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 2)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 16)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(tostring(pkg_table2.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table2.body.logout.count, 2)
ASSERT_EQ(pkg_table2.body.logout.attr, {-1, 0})
ASSERT_EQ(pkg_table2.body.ext1, nil)
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 2)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 16)
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table3.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.login, nil)
ASSERT_EQ(tostring(pkg_table3.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table3.body.logout.count, 2)
ASSERT_EQ(pkg_table3.body.logout.attr, {-1, 0})
ASSERT_EQ(pkg_table3.body.ext1, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_2(self)
self.count = 1 + self.count
pkg_table2, pkg_table3 = self:LoadMetalib(1, "testxxx.tdr", 2)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 2)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 16)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
local ret = -1
ASSERT_EQ(ret, -1)
ASSERT_EQ(tostring(pkg_table2.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table2.body.logout.count, 2)
ASSERT_EQ(pkg_table2.body.logout.attr, {-1, 0})
ASSERT_EQ(pkg_table2.body.ext1, nil)
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 2)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 16)
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table3.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table3.body.login, nil)
local ret = -1
ASSERT_EQ(ret, -1)
ASSERT_EQ(tostring(pkg_table3.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table3.body.logout.count, 2)
ASSERT_EQ(pkg_table3.body.logout.attr, {-1, 0})
ASSERT_EQ(pkg_table3.body.ext1, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_3(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2, pkg_table3 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 3)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 3)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 222)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(libtdrlua.tdrip2str(pkg_table2.head.srcIp), "127.0.0.1")
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.logout, nil)
ASSERT_EQ(libtdrlua.tdrdate2str(pkg_table2.body.xxx.typeTester.date), "2015-09-08")
ASSERT_EQ(libtdrlua.tdrtime2str(pkg_table2.body.xxx.typeTester.time), " 22:17:59")
ASSERT_EQ(pkg_table2.body.xxx.typeTester.time, libtdrlua.str2tdrtime("22:17:59"))
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8, -1)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.uint8Array, {0, 23, 255})
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8VarArrayRefer, 2)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8VarArray, {-128, 127})
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.uintArray, {0, 1721, 0xFFFFFFFF}) --测试不过,0xFFFFFFFF解包后变长了0x80000000
ASSERT_EQ(pkg_table2.body.xxx.typeTester.intVarArray, {-0x80000000})
ASSERT_EQ(pkg_table2.body.xxx.typeTester.strArray, {"Francis", "Francis"})
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.uint64), "4503599627370495") --0xFFFFFFFFFFFFF
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.int64Array, {-9223372036854775808, 4503599627370495, 9223372036854775807}) --{-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},,测试不过,解包后0x7FFFFFFFFFFFFFFF变长了-9223372036854775808
ASSERT_EQ(pkg_table.body.xxx.typeTester.int64Array[3], 0x7FFFFFFFFFFFFFFF)--此处验证打包前是ok的
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.float, 0xFFFFFFFF) --此处验证不过,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table.body.xxx.typeTester.float, 0xFFFFFFFF)--此处验证打包前是ok的
---会存在精度问题,实际为{-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[1]), "-3.4028234663853e+38")
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[2]), "1.1754943508223e-38")
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[3]), "3.4028234663853e+38")
ASSERT_EQ(pkg_table2.body.xxx.typeTester.double, 2.2250738585072014e-308)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.doubleArray, {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308})
ASSERT_EQ(string.sub(tostring(pkg_table2.body.xxx.boundary),1, 4), "-1.1")
ASSERT_EQ(pkg_table2.body.xxx.selector, 1)
print("to_string filed1:" .. table_to_string(pkg_table2.body.xxx.innerUnion.field1[1]))
--ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[1], {unit64 = 0x0FFFFFFFFFFFFFFF, uint = 0xFFFFFFFF})
ASSERT_EQ(type(pkg_table.body.xxx.innerUnion.field1[1]), 'table')
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(tostring(pkg_table2.body.xxx.innerUnion.field1[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(tostring(pkg_table2.body.xxx.innerUnion.field1[2].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(pkg_table2.body.xxx.structArray.count, 1)
ASSERT_EQ(tostring(pkg_table2.body.xxx.structArray.array[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table2.body.xxx.structArray.array[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table2.body.xxx.structArray.array[2], nil)
ASSERT_EQ(string.sub(tostring(pkg_table2.body.xxx.boundary2),1, 8), "1.111111")
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 3)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 222)
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(libtdrlua.tdrip2str(pkg_table3.head.srcIp), "127.0.0.1")
ASSERT_EQ(pkg_table3.body.login, nil)
ASSERT_EQ(pkg_table3.body.logout, nil)
ASSERT_EQ(libtdrlua.tdrdate2str(pkg_table3.body.xxx.typeTester.date), "2015-09-08")
ASSERT_EQ(libtdrlua.tdrtime2str(pkg_table3.body.xxx.typeTester.time), " 22:17:59")
ASSERT_EQ(pkg_table3.body.xxx.typeTester.time, libtdrlua.str2tdrtime("22:17:59"))
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8, -1)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.uint8Array, {0, 23, 255})
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8VarArrayRefer, 2)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8VarArray, {-128, 127})
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.uintArray, {0, 1721, 0xFFFFFFFF}) --测试不过,0xFFFFFFFF解包后变长了0x80000000
ASSERT_EQ(pkg_table3.body.xxx.typeTester.intVarArray, {-0x80000000})
ASSERT_EQ(pkg_table3.body.xxx.typeTester.strArray, {"Francis", "Francis"})
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.uint64), "4503599627370495") --0xFFFFFFFFFFFFF
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.int64Array, {-9223372036854775808, 4503599627370495, 9223372036854775807}) --{-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},,测试不过,解包后0x7FFFFFFFFFFFFFFF变长了-9223372036854775808
ASSERT_EQ(pkg_table.body.xxx.typeTester.int64Array[3], 0x7FFFFFFFFFFFFFFF)--此处验证打包前是ok的
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.float, 0xFFFFFFFF) --此处验证不过,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table.body.xxx.typeTester.float, 0xFFFFFFFF)--此处验证打包前是ok的
---会存在精度问题,实际为{-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[1]), "-3.4028234663853e+38")
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[2]), "1.1754943508223e-38")
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[3]), "3.4028234663853e+38")
ASSERT_EQ(pkg_table3.body.xxx.typeTester.double, 2.2250738585072014e-308)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.doubleArray, {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308})
ASSERT_EQ(string.sub(tostring(pkg_table3.body.xxx.boundary),1, 4), "-1.1")
ASSERT_EQ(pkg_table3.body.xxx.selector, 1)
print("to_string filed1:" .. table_to_string(pkg_table3.body.xxx.innerUnion.field1[1]))
--ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[1], {unit64 = 0x0FFFFFFFFFFFFFFF, uint = 0xFFFFFFFF})
ASSERT_EQ(type(pkg_table.body.xxx.innerUnion.field1[1]), 'table')
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(tostring(pkg_table3.body.xxx.innerUnion.field1[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(tostring(pkg_table3.body.xxx.innerUnion.field1[2].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(pkg_table3.body.xxx.structArray.count, 1)
ASSERT_EQ(tostring(pkg_table3.body.xxx.structArray.array[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table3.body.xxx.structArray.array[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table3.body.xxx.structArray.array[2], nil)
ASSERT_EQ(string.sub(tostring(pkg_table3.body.xxx.boundary2),1, 8), "1.111111")
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_3(self)
self.count = 1 + self.count
pkg_table2, pkg_table3 = self:LoadMetalib(1, "testxxx.tdr", 3)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 3)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 222)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.logout, nil)
ASSERT_EQ(libtdrlua.tdrdate2str(pkg_table2.body.xxx.typeTester.date), "2015-09-08")
ASSERT_EQ(libtdrlua.tdrtime2str(pkg_table2.body.xxx.typeTester.time), " 22:17:59")
ASSERT_EQ(pkg_table2.body.xxx.typeTester.time, libtdrlua.str2tdrtime("22:17:59"))
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8, -1)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.uint8Array, {0, 23, 255})
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8VarArrayRefer, 2)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.int8VarArray, {-128, 127})
ASSERT_EQ(pkg_table.body.xxx.typeTester.uintArray, {0, 1721, 0xFFFFFFFF})
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.uintArray, {0, 1721, 0xFFFFFFFF}) --测试不过,0xFFFFFFFF解包后变长了0x80000000
ASSERT_EQ(pkg_table2.body.xxx.typeTester.intVarArray, {-0x80000000})
ASSERT_EQ(pkg_table2.body.xxx.typeTester.strArray, {"Francis", "Francis"})
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.uint64), "4503599627370495") --0xFFFFFFFFFFFFF
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.int64Array, {-9223372036854775808, 4503599627370495, 9223372036854775807}) --{-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},,测试不过,解包后0x7FFFFFFFFFFFFFFF变长了-9223372036854775808
ASSERT_EQ(pkg_table.body.xxx.typeTester.int64Array[3], 0x7FFFFFFFFFFFFFFF)--此处验证打包前是ok的
--ASSERT_EQ(pkg_table2.body.xxx.typeTester.float, 0xFFFFFFFF) --此处验证不过,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table.body.xxx.typeTester.float, 0xFFFFFFFF)--此处验证打包前是ok的
---会存在精度问题,实际为{-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[1]), "-3.4028234663853e+38")
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[2]), "1.1754943508223e-38")
ASSERT_EQ(tostring(pkg_table2.body.xxx.typeTester.floatArray[3]), "3.4028234663853e+38")
ASSERT_EQ(pkg_table2.body.xxx.typeTester.double, 2.2250738585072014e-308)
ASSERT_EQ(pkg_table2.body.xxx.typeTester.doubleArray, {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308})
ASSERT_EQ(string.sub(tostring(pkg_table2.body.xxx.boundary),1, 4), "-1.1")
ASSERT_EQ(pkg_table2.body.xxx.selector, 1)
print("to_string filed1:" .. table_to_string(pkg_table2.body.xxx.innerUnion.field1[1]))
--ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[1], {unit64 = 0x0FFFFFFFFFFFFFFF, uint = 0xFFFFFFFF})
ASSERT_EQ(type(pkg_table.body.xxx.innerUnion.field1[1]), 'table')
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(tostring(pkg_table2.body.xxx.innerUnion.field1[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(tostring(pkg_table2.body.xxx.innerUnion.field1[2].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
ASSERT_EQ(pkg_table2.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(pkg_table2.body.xxx.structArray.count, 1)
ASSERT_EQ(tostring(pkg_table2.body.xxx.structArray.array[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table2.body.xxx.structArray.array[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table2.body.xxx.structArray.array[2], nil)
ASSERT_EQ(string.sub(tostring(pkg_table2.body.xxx.boundary2),1, 8), "1.111111")
ASSERT_EQ(pkg_table3.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table3.head.msgid), "10000001")
ASSERT_EQ(pkg_table3.head.cmd, 3)
ASSERT_EQ(pkg_table3.head.version, 3)
ASSERT_EQ(pkg_table3.head.bodyLen, 222)
ASSERT_EQ(pkg_table3.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(libtdrlua.tdrip2str(pkg_table3.head.srcIp), "127.0.0.1")
ASSERT_EQ(pkg_table3.body.login, nil)
ASSERT_EQ(pkg_table3.body.logout, nil)
ASSERT_EQ(libtdrlua.tdrdate2str(pkg_table3.body.xxx.typeTester.date), "2015-09-08")
ASSERT_EQ(libtdrlua.tdrtime2str(pkg_table3.body.xxx.typeTester.time), " 22:17:59")
ASSERT_EQ(pkg_table3.body.xxx.typeTester.time, libtdrlua.str2tdrtime("22:17:59"))
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8, -1)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.uint8Array, {0, 23, 255})
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8VarArrayRefer, 2)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.int8VarArray, {-128, 127})
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.uintArray, {0, 1721, 0xFFFFFFFF}) --测试不过,0xFFFFFFFF解包后变长了0x80000000
ASSERT_EQ(pkg_table3.body.xxx.typeTester.intVarArray, {-0x80000000})
ASSERT_EQ(pkg_table3.body.xxx.typeTester.strArray, {"Francis", "Francis"})
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.uint64), "4503599627370495") --0xFFFFFFFFFFFFF
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.int64Array, {-9223372036854775808, 4503599627370495, 9223372036854775807}) --{-0x8000000000000000, 0xFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF},,测试不过,解包后0x7FFFFFFFFFFFFFFF变长了-9223372036854775808
ASSERT_EQ(pkg_table.body.xxx.typeTester.int64Array[3], 0x7FFFFFFFFFFFFFFF)--此处验证打包前是ok的
--ASSERT_EQ(pkg_table3.body.xxx.typeTester.float, 0xFFFFFFFF) --此处验证不过,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table.body.xxx.typeTester.float, 0xFFFFFFFF)--此处验证打包前是ok的
---会存在精度问题,实际为{-3.40282346e+38, 1.17549435e-38, 3.40282346e+38}
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[1]), "-3.4028234663853e+38")
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[2]), "1.1754943508223e-38")
ASSERT_EQ(tostring(pkg_table3.body.xxx.typeTester.floatArray[3]), "3.4028234663853e+38")
ASSERT_EQ(pkg_table3.body.xxx.typeTester.double, 2.2250738585072014e-308)
ASSERT_EQ(pkg_table3.body.xxx.typeTester.doubleArray, {-1.7976931348623157e+308, -2.2250738585072014e-308, 1.7976931348623157e+308})
ASSERT_EQ(string.sub(tostring(pkg_table3.body.xxx.boundary),1, 4), "-1.1")
ASSERT_EQ(pkg_table3.body.xxx.selector, 1)
print("to_string filed1:" .. table_to_string(pkg_table3.body.xxx.innerUnion.field1[1]))
--ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[1], {unit64 = 0x0FFFFFFFFFFFFFFF, uint = 0xFFFFFFFF})
ASSERT_EQ(type(pkg_table.body.xxx.innerUnion.field1[1]), 'table')
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint64, 0x0FFFFFFFFFFFFFFF)
ASSERT_EQ(pkg_table.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(tostring(pkg_table3.body.xxx.innerUnion.field1[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(tostring(pkg_table3.body.xxx.innerUnion.field1[2].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
ASSERT_EQ(pkg_table3.body.xxx.innerUnion.field1[2].uint, 0)
ASSERT_EQ(pkg_table3.body.xxx.structArray.count, 1)
ASSERT_EQ(tostring(pkg_table3.body.xxx.structArray.array[1].uint64 - 0x0FFFFFFFFFFFFFFF), "0")
--ASSERT_EQ(pkg_table3.body.xxx.structArray.array[1].uint, 0xFFFFFFFF) --这个值解包后有问题,ASSERT_EQ failed --> left:4294967296, right:4294967295.
ASSERT_EQ(pkg_table3.body.xxx.structArray.array[2], nil)
ASSERT_EQ(string.sub(tostring(pkg_table3.body.xxx.boundary2),1, 8), "1.111111")
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_4(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 4)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 4)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 4)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext1, -1)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_4(self)
self.count = 1 + self.count
pkg_table2 = self:LoadMetalib(1, "testxxx.tdr", 5)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 5)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 4)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext1, -1)
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_5(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 70)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 70)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 3)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext2, {0, 1, 2})
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_5(self)
self.count = 1 + self.count
pkg_table2 = self:LoadMetalib(1, "testxxx.tdr", 80)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 80)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 3)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext2, {0, 1, 2})
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_6(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 75)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 75)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 3)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext2, {0, 1, 2})
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_6(self)
self.count = 1 + self.count
pkg_table2 = self:LoadMetalib(1, "testxxx.tdr", 81)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 81)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 4)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext1, -1)
end
function CMyTestCaseLuaTdr.CaseLoadMetalib_7(self)
self.count = 1 + self.count
if CS.LuaTestCommon.android_platform == true then
return
end
pkg_table2 = self:LoadMetalib(0, CS.LuaTestCommon.xxxtdrfilepath, 15)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 15)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 24)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext3, {"Francis", "Francis"})
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBuff_7(self)
self.count = 1 + self.count
pkg_table2 = self:LoadMetalib(1, "testxxx.tdr", 100)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 100)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 12)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
ASSERT_EQ(pkg_table2.body.ext4, "Francis")
end
function CMyTestCaseLuaTdr.CaseLoadMetalibNoExistTdr(self)
self.count = 1 + self.count
local ret_code, err_msg = libtdrlua.load_metalib("noexist.tdr")
ASSERT_EQ(ret_code, -2113862584)
print("CaseLoadMetalibNoExistTdr err_msg:" .. err_msg)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibErrorTdrFile(self)
self.count = 1 + self.count
local ret_code, err_msg = libtdrlua.load_metalib("test2.lua")
ASSERT_EQ(ret_code, -2113862584)
print("CaseLoadMetalibErrorTdrFile err_msg:" .. err_msg)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibMultiTimes(self)
self.count = 1 + self.count
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
local ret_code2, metalib2 = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(ret_code2, 0)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg2 = libtdrlua.free_metalib(metalib2)
ASSERT_EQ(err_msg2, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibDiffTdrFile(self)
self.count = 1 + self.count
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local tdrmeta2 = CS.UnityEngine.Resources.Load("testxxx2.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
local ret_code2, metalib2 = libtdrlua.load_metalib_buf(tdrmeta2)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(ret_code2, 0)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg2 = libtdrlua.free_metalib(metalib2)
ASSERT_EQ(err_msg2, nil)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBufFromEmptyStr(self)
self.count = 1 + self.count
local ret_code, metalib = libtdrlua.load_metalib_buf("")
ASSERT_EQ(ret_code, -2113862536)
end
function CMyTestCaseLuaTdr.CaseLoadMetalibBufFromNoTdrStr(self)
self.count = 1 + self.count
local ret_code, metalib = libtdrlua.load_metalib_buf("testtdr")
ASSERT_EQ(ret_code, -2113862536)
end
function CMyTestCaseLuaTdr.CaseGetMeta(self)
--加载meta元数据库
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
print("libtdrlua.load_metalib ok")
------------------------------------------------------------------------
-- API - get_meta
-- return value - ret_code, meta/err_msg
----------------------------------------------------------------------
local ret_code, meta = libtdrlua.get_meta(metalib, "PkgBody")
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "PkgNoExist")
ASSERT_EQ(ret_code, -1)
local ret_code, meta = libtdrlua.get_meta(metalib, "PKG_ID")
ASSERT_EQ(ret_code, -1)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseTable2Buf_1(self)
--长度等于实际长度
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
buf_size = 71
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(used_size, buf_size)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size, 0)
print("table2buf pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseTable2Buf_2(self)
--buf 和 len 小于pkg_table实际长度
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
buf_size = 56
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, -2113862654)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseTable2Buf_3(self)
--4.不设置version参数打包
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
local buf_size = 71
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(used_size, buf_size)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size)
print("table2buf pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseTable2Buf_4(self)
--5.version参数值小于等于meta中设置的version
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
local buf_size = 71
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
--Struct Pkg有设置versionindicator="head.version",因此会按照打包时的version解包,buf2table输入的version不会生效
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 2)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size, 3)
print("table2buf pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 2)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, 0) --srcIp的version为3
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
local ret_code, meta = libtdrlua.get_meta(metalib, "PkgHead")
ASSERT_EQ(ret_code, 0)
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table.head, buf, buf_size, 3)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size, 2)
print("table2buf pkghead pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.msgid), "10000001")
ASSERT_EQ(pkg_table2.cmd, 1)
ASSERT_EQ(pkg_table2.version, 2)
ASSERT_EQ(pkg_table2.bodyLen, 0)
ASSERT_EQ(pkg_table2.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.srcIp, 0) --srcIp的version为3
--6.version参数值大于meta中设置的version
local ret_code, pkg_table3, used_size2 = libtdrlua.buf2table(meta, buf, used_size, 4)
print("table2buf pkghead pkg_table3: " .. table_to_string(pkg_table3))
ASSERT_EQ(ret_code, 0)
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table.head, buf, buf_size, 4)
ASSERT_EQ(ret_code, 0)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseBuf2Table_1(self)
--2.len 大于buf长度,version为0
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
buf_size = 128
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size + 10, 0)
print("table2buf pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
--3.len小于message(buf)长度
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta, buf, used_size - 10, 0)
ASSERT_EQ(ret_code, -2113862654)
--4.meta和buf中数据结构定义不一致
local ret_code, meta_2 = libtdrlua.get_meta(metalib, "PkgBodyPrevious")
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2, used_size2 = libtdrlua.buf2table(meta_2, buf, used_size, 0)
ASSERT_EQ(ret_code, -2113862552)
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseStr2Buf(self)
--1. str为空
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
local buf_size = 71
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
pkg_table.head.cmd = 1
local ret_code, meta = libtdrlua.get_meta(metalib, "PkgHead")
ASSERT_EQ(ret_code, 0)
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table.head, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, str = libtdrlua.buf2str(buf, used_size)
ASSERT_EQ(ret_code, 0)
local ret_code, err_msg = libtdrlua.str2table(meta, "", 3)
ASSERT_EQ(ret_code, -2113862552)
--3.meta和str中数据结构定义不一致
local ret_code, meta2 = libtdrlua.get_meta(metalib, "PkgBody")
local ret_code, err_msg = libtdrlua.str2table(meta2, str, 0)
ASSERT_EQ(ret_code, -2113862552)
--4. version不设置
local ret_code, pkg_table2 = libtdrlua.str2table(meta, str)
ASSERT_EQ(ret_code, 0)
--5. version小于等于meta中version值
local ret_code, pkg_table3 = libtdrlua.str2table(meta, str, 2)
ASSERT_EQ(ret_code, 0)
--6. version大于meta中version值
local ret_code, pkg_table4 = libtdrlua.str2table(meta, str, 2)
ASSERT_EQ(ret_code, 0)
print("table2buf pkghead pkg_table2: " .. table_to_string(pkg_table2))
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.msgid), "10000001")
ASSERT_EQ(pkg_table2.cmd, 1)
ASSERT_EQ(pkg_table2.version, 3)
ASSERT_EQ(pkg_table2.bodyLen, 0)
ASSERT_EQ(pkg_table2.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseZZZRefer_1(self)
--2 某数组refer的值大于数组count,调用table2buf函数
self.count = 1 + self.count
pkg_table.body.logout.count = 4
pkg_table.head.cmd = 2
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
buf_size = 128
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta = libtdrlua.get_meta(metalib, "Pkg")
ASSERT_EQ(ret_code, 0)
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, -2113862521)
--3 某数组refer的值等于数组count,调用table2buf打包和buf2table解包
pkg_table.body.logout.count = 3
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 2)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 17)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
local ret = -1
ASSERT_EQ(ret, -1)
ASSERT_EQ(tostring(pkg_table2.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table2.body.logout.count, 3)
ASSERT_EQ(pkg_table2.body.logout.attr, {-1, 0, 1})
ASSERT_EQ(pkg_table2.body.ext1, nil)
-- 4 某数组refer的值等于0,调用table2buf打包和buf2table解包
pkg_table.body.logout.count = 0
local ret_code, used_size = libtdrlua.table2buf(meta, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 2)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 14)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.login, nil)
local ret = -1
ASSERT_EQ(ret, -1)
ASSERT_EQ(tostring(pkg_table2.body.logout.reason + 1), "0")
ASSERT_EQ(pkg_table2.body.logout.count, 0)
ASSERT_EQ(pkg_table2.body.logout.attr, {})
ASSERT_EQ(pkg_table2.body.ext1, nil)
pkg_table.body.logout.count = 2
pkg_table.head.cmd = 1
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseZZZZVersion_1(self)
--4.高版本多2个字段,用高版本meta,打包时传入低版本version, 然后用低版本meta解包(version为0)
self.count = 1 + self.count
pkg_table.head.cmd = 1
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib_v3 = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
local tdrmeta2 = CS.UnityEngine.Resources.Load("testxxx2.tdr").bytes
local ret_code, metalib_v4 = libtdrlua.load_metalib_buf(tdrmeta2)
ASSERT_EQ(ret_code, 0)
buf_size = 128
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta_v3 = libtdrlua.get_meta(metalib_v3, "Pkg")
ASSERT_EQ(ret_code, 0)
local ret_code, meta_v4 = libtdrlua.get_meta(metalib_v4, "Pkg")
ASSERT_EQ(ret_code, 0)
local ret_code, used_size = libtdrlua.table2buf(meta_v4, pkg_table_v4, buf, buf_size, 3)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta_v3, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.head.magic, 32767)
ASSERT_EQ(tostring(pkg_table2.head.msgid), "10000001")
ASSERT_EQ(pkg_table2.head.cmd, 1)
ASSERT_EQ(pkg_table2.head.version, 3)
ASSERT_EQ(pkg_table2.head.bodyLen, 39)
ASSERT_EQ(pkg_table2.head.datetime, libtdrlua.str2tdrdatetime("2015-09-08 21:17:59"))
ASSERT_EQ(pkg_table2.head.srcIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.head.destIp, nil)
ASSERT_EQ(pkg_table2.body.login.name, "FrancisHe")
ASSERT_EQ(pkg_table2.body.login.pass, "123456")
ASSERT_EQ(pkg_table2.body.login.zone, "Japan")
ASSERT_EQ(pkg_table2.body.login.destIp, libtdrlua.str2tdrip("127.0.0.1"))
ASSERT_EQ(pkg_table2.body.ext1, nil)
--1.1 pack低版本(meta对应低版本),unpack高版本(meta对应高版本)
local ret_code, used_size = libtdrlua.table2buf(meta_v3, pkg_table, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta_v4, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
--1.2 pack高版本,unpack低版本
local ret_code, used_size = libtdrlua.table2buf(meta_v4, pkg_table_v4, buf, buf_size, 0)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta_v3, buf, used_size, 0)
ASSERT_EQ(ret_code, -2113862544)
pkg_table.head.cmd = 1
local err_msg = libtdrlua.free_metalib(metalib_v3)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.free_metalib(metalib_v4)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end
function CMyTestCaseLuaTdr.CaseZZZZRandom(self)
--6.同一个结构类 entry 类型乱序排列,调用table2buf打包和buf2table解包
self.count = 1 + self.count
local tdrmeta = CS.UnityEngine.Resources.Load("testxxx.tdr").bytes
local ret_code, metalib = libtdrlua.load_metalib_buf(tdrmeta)
ASSERT_EQ(ret_code, 0)
buf_size = 128
local ret_code, buf = libtdrlua.bufalloc(buf_size)
ASSERT_EQ(ret_code, 0)
local ret_code, meta_v1 = libtdrlua.get_meta(metalib, "TestInnerStruct1")
ASSERT_EQ(ret_code, 0)
local ret_code, meta_v2 = libtdrlua.get_meta(metalib, "TestInnerStruct2")
ASSERT_EQ(ret_code, 0)
pkg_table_v1 = {
int8 = 127,
double = 2.2250738585072114e-308,
float = 1,
int16 = 32767,
int32Array = {-0x7FFFFFFF, 0, 0x7FFFFFFF},
}
pkg_table_v2 = {
double = 2.2250738585072114e-308,
int8 = 127,
int32Array = {-0x7FFFFFFF, 0, 0x7FFFFFFF},
int16 = 32767,
float = 1,
}
local ret_code, used_size = libtdrlua.table2buf(meta_v1, pkg_table_v1, buf, buf_size, 3)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta_v1, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.int8, 127)
ASSERT_EQ(pkg_table2.double, 2.2250738585072114e-308)
ASSERT_EQ(pkg_table2.float, 1)
ASSERT_EQ(pkg_table2.int16, 32767)
ASSERT_EQ(pkg_table2.int32Array, {-0x7FFFFFFF, 0, 0x7FFFFFFF})
local ret_code, used_size = libtdrlua.table2buf(meta_v2, pkg_table_v2, buf, buf_size, 3)
ASSERT_EQ(ret_code, 0)
local ret_code, pkg_table2 = libtdrlua.buf2table(meta_v2, buf, used_size, 0)
ASSERT_EQ(ret_code, 0)
ASSERT_EQ(pkg_table2.int8, 127)
ASSERT_EQ(pkg_table2.double, 2.2250738585072114e-308)
ASSERT_EQ(pkg_table2.float, 1)
ASSERT_EQ(pkg_table2.int16, 32767)
ASSERT_EQ(pkg_table2.int32Array, {-0x7FFFFFFF, 0, 0x7FFFFFFF})
local err_msg = libtdrlua.free_metalib(metalib)
ASSERT_EQ(err_msg, nil)
local err_msg = libtdrlua.buffree(buf)
ASSERT_EQ(err_msg, nil)
end | xLua/Test/UnitTest/StreamingAssets/luaTdrTest.lua/0 | {
"file_path": "xLua/Test/UnitTest/StreamingAssets/luaTdrTest.lua",
"repo_id": "xLua",
"token_count": 28881
} | 2,070 |
#if !XLUA_GENERAL
using UnityEngine;
#endif
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using System.IO;
public class tableValue1ClassEqual{
public int key1;
public int key2;
public bool key3;
public List<int> tableValueInclude;
}
public class tableValue1ClassLess{
public int key1;
public int key2;
public tableValue1ClassLess()
{
}
}
public class tableValue1ClassMore{
public int key1;
public int key2;
public bool key3;
public int key4;
}
public class tableValue1ClassPrivate{
public int key1;
private int key2;
public bool key3;
public int Get()
{
return key2;
}
public void Set(int value)
{
this.key2 = value;
}
}
public class tableValue1ClassParamConstucter{
public int key1;
public int key2;
public bool key3;
public tableValue1ClassParamConstucter(int key1, int key2, bool key3)
{
this.key1 = key1;
this.key2 = key2;
this.key3 = key3;
}
}
public class tableValue1ClassTwoConstructer{
public int key1;
public int key2;
public bool key3;
public tableValue1ClassTwoConstructer()
{
}
public tableValue1ClassTwoConstructer(int key1, int key2, bool key3)
{
this.key1 = key1;
this.key2 = key2;
this.key3 = key3;
}
}
public class tableValue1ClassException{
public int key1;
public int key2;
public bool key3;
public tableValue1ClassException()
{
throw new Exception("constructor throw exception.");
}
}
public class tableValue2Class
{
public bool kv1;
public string kv3;
public int kv2;
}
public class tableValue4Class
{
public int k1;
public int k2;
public int k3;
public int k4;
public int k5;
}
[CSharpCallLua]
public interface tableVarIncludeInf
{
int ikey1 { get; set; }
int ikey2 { get; set; }
}
[CSharpCallLua]
public interface tableValue1InfEqual
{
int key1 { get; set; }
int key2 { get; set; }
bool key3 { get; set; }
tableVarIncludeInf tableVarInclude {get; set; }
int sub(int a, int b);
}
[CSharpCallLua]
public interface tableValue1InfMore
{
int key1 { get; set; }
int key2 { get; set; }
bool key3 { get; set; }
string key4 { get; set;}
int sub(int a, int b);
}
[CSharpCallLua]
public interface tableValue1InfLess
{
int key1 { get; set; }
int key2 { get; set; }
int sub(int a, int b);
}
[CSharpCallLua]
public interface tableValue1InfTypeDiff
{
string key1 { get; set; }
int key2 { get; set; }
int sub(int a, int b);
}
[CSharpCallLua]
public interface tableValue2Inf
{
bool kv1 { get; set; }
string kv2 { get; set; }
int kv3 { get; set; }
}
[CSharpCallLua]
public delegate void FuncSelfINcreaseDelegate();
[CSharpCallLua]
public delegate int FuncAddTableDelegate(LuaTable a);
[CSharpCallLua]
public delegate int FuncAdd2elegate(Dictionary<string, int> a);
[CSharpCallLua]
public delegate Action GetFuncIncreaseDelegate();
[CSharpCallLua]
public delegate bool FuncReturnMultivaluesDelegate1(out string str, out tableValue4Class table);
[CSharpCallLua]
public delegate void FuncReturnMultivaluesDelegate2(out bool update, out string str, out tableValue4Class table);
[CSharpCallLua]
public delegate void FuncReturnMultivaluesDelegate3(out bool update, out string str, out tableValue4Class table, out int a);
[CSharpCallLua]
public delegate bool FuncReturnMultivaluesDelegate4(out string str);
[CSharpCallLua]
public delegate void FuncReturnMultivaluesDelegate31(out bool update, out string str, out tableValue4Class table, out tableValue4Class a);
[CSharpCallLua]
public delegate void FuncMultiParamsDelegate(ref bool a, ref int b, ref string c, out int d);
/*
[CSharpCallLua]
public delegate Action FuncMultiParams2Delegate(ref bool a, int b, out int c);
*/
[CSharpCallLua]
public delegate void FuncMultiParams3Delegate(out int c, int b, ref bool a);
[CSharpCallLua]
public delegate void FuncMultiParams3Delegate2(int b, out int c, ref bool a);
[CSharpCallLua]
public delegate int FucnVarParamsDelegate(int a, int b);
[CSharpCallLua]
public delegate string FucnReadFileDelegate(string filename);
[CSharpCallLua]
public delegate System.Object FuncReturnObjectDelegate(int type);
| xLua/Test/UnitTest/xLuaTest/CSharpCallLua/CSObjectForTestCSCallLua.cs/0 | {
"file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/CSObjectForTestCSCallLua.cs",
"repo_id": "xLua",
"token_count": 1460
} | 2,071 |
fileFormatVersion: 2
guid: 76dffed6dedc93a4a93f70367637ac20
timeCreated: 1483528414
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TCForTestCSCallLua.cs.meta/0 | {
"file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TCForTestCSCallLua.cs.meta",
"repo_id": "xLua",
"token_count": 100
} | 2,072 |
fileFormatVersion: 2
guid: 9331fb732c3f3e34aa1642e545db60f4
folderAsset: yes
timeCreated: 1483527547
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| xLua/Test/UnitTest/xLuaTest/Resources.meta/0 | {
"file_path": "xLua/Test/UnitTest/xLuaTest/Resources.meta",
"repo_id": "xLua",
"token_count": 76
} | 2,073 |
/*
** $Id: lapi.h,v 2.9 2015/03/06 19:49:50 roberto Exp $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
#ifndef lapi_h
#define lapi_h
#include "llimits.h"
#include "lstate.h"
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
"stack overflow");}
#define adjustresults(L,nres) \
{ if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
"not enough elements in the stack")
#endif
| xLua/WebGLPlugins/lapi.h/0 | {
"file_path": "xLua/WebGLPlugins/lapi.h",
"repo_id": "xLua",
"token_count": 241
} | 2,074 |
/*
** $Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
#define lfunc_c
#define LUA_CORE
#include "lprefix.h"
#include <stddef.h>
#include "lua.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
CClosure *luaF_newCclosure (lua_State *L, int n) {
GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));
CClosure *c = gco2ccl(o);
c->nupvalues = cast_byte(n);
return c;
}
LClosure *luaF_newLclosure (lua_State *L, int n) {
GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));
LClosure *c = gco2lcl(o);
c->p = NULL;
c->nupvalues = cast_byte(n);
while (n--) c->upvals[n] = NULL;
return c;
}
/*
** fill a closure with new closed upvalues
*/
void luaF_initupvals (lua_State *L, LClosure *cl) {
int i;
for (i = 0; i < cl->nupvalues; i++) {
UpVal *uv = luaM_new(L, UpVal);
uv->refcount = 1;
uv->v = &uv->u.value; /* make it closed */
setnilvalue(uv->v);
cl->upvals[i] = uv;
}
}
UpVal *luaF_findupval (lua_State *L, StkId level) {
UpVal **pp = &L->openupval;
UpVal *p;
UpVal *uv;
lua_assert(isintwups(L) || L->openupval == NULL);
while (*pp != NULL && (p = *pp)->v >= level) {
lua_assert(upisopen(p));
if (p->v == level) /* found a corresponding upvalue? */
return p; /* return it */
pp = &p->u.open.next;
}
/* not found: create a new upvalue */
uv = luaM_new(L, UpVal);
uv->refcount = 0;
uv->u.open.next = *pp; /* link it to list of open upvalues */
uv->u.open.touched = 1;
*pp = uv;
uv->v = level; /* current value lives in the stack */
if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
L->twups = G(L)->twups; /* link it to the list */
G(L)->twups = L;
}
return uv;
}
void luaF_close (lua_State *L, StkId level) {
UpVal *uv;
while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
lua_assert(upisopen(uv));
L->openupval = uv->u.open.next; /* remove from 'open' list */
if (uv->refcount == 0) /* no references? */
luaM_free(L, uv); /* free upvalue */
else {
setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */
uv->v = &uv->u.value; /* now current value lives here */
luaC_upvalbarrier(L, uv);
}
}
}
Proto *luaF_newproto (lua_State *L) {
GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
Proto *f = gco2p(o);
f->k = NULL;
f->sizek = 0;
f->p = NULL;
f->sizep = 0;
f->code = NULL;
f->cache = NULL;
f->sizecode = 0;
f->lineinfo = NULL;
f->sizelineinfo = 0;
f->upvalues = NULL;
f->sizeupvalues = 0;
f->numparams = 0;
f->is_vararg = 0;
f->maxstacksize = 0;
f->locvars = NULL;
f->sizelocvars = 0;
f->linedefined = 0;
f->lastlinedefined = 0;
f->source = NULL;
return f;
}
void luaF_freeproto (lua_State *L, Proto *f) {
luaM_freearray(L, f->code, f->sizecode);
luaM_freearray(L, f->p, f->sizep);
luaM_freearray(L, f->k, f->sizek);
luaM_freearray(L, f->lineinfo, f->sizelineinfo);
luaM_freearray(L, f->locvars, f->sizelocvars);
luaM_freearray(L, f->upvalues, f->sizeupvalues);
luaM_free(L, f);
}
/*
** Look for n-th local variable at line 'line' in function 'func'.
** Returns NULL if not found.
*/
const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
int i;
for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
if (pc < f->locvars[i].endpc) { /* is variable active? */
local_number--;
if (local_number == 0)
return getstr(f->locvars[i].varname);
}
}
return NULL; /* not found */
}
| xLua/WebGLPlugins/lfunc.c/0 | {
"file_path": "xLua/WebGLPlugins/lfunc.c",
"repo_id": "xLua",
"token_count": 1688
} | 2,075 |
/*
** $Id: lopcodes.h,v 1.149 2016/07/19 17:12:21 roberto Exp $
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
#ifndef lopcodes_h
#define lopcodes_h
#include "llimits.h"
/*===========================================================================
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits.
Instructions can have the following fields:
'A' : 8 bits
'B' : 9 bits
'C' : 9 bits
'Ax' : 26 bits ('A', 'B', and 'C' together)
'Bx' : 18 bits ('B' and 'C' together)
'sBx' : signed Bx
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding
unsigned argument.
===========================================================================*/
enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */
/*
** size and position of opcode arguments.
*/
#define SIZE_C 9
#define SIZE_B 9
#define SIZE_Bx (SIZE_C + SIZE_B)
#define SIZE_A 8
#define SIZE_Ax (SIZE_C + SIZE_B + SIZE_A)
#define SIZE_OP 6
#define POS_OP 0
#define POS_A (POS_OP + SIZE_OP)
#define POS_C (POS_A + SIZE_A)
#define POS_B (POS_C + SIZE_C)
#define POS_Bx POS_C
#define POS_Ax POS_A
/*
** limits for opcode arguments.
** we use (signed) int to manipulate most arguments,
** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
*/
#if SIZE_Bx < LUAI_BITSINT-1
#define MAXARG_Bx ((1<<SIZE_Bx)-1)
#define MAXARG_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */
#else
#define MAXARG_Bx MAX_INT
#define MAXARG_sBx MAX_INT
#endif
#if SIZE_Ax < LUAI_BITSINT-1
#define MAXARG_Ax ((1<<SIZE_Ax)-1)
#else
#define MAXARG_Ax MAX_INT
#endif
#define MAXARG_A ((1<<SIZE_A)-1)
#define MAXARG_B ((1<<SIZE_B)-1)
#define MAXARG_C ((1<<SIZE_C)-1)
/* creates a mask with 'n' 1 bits at position 'p' */
#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
/* creates a mask with 'n' 0 bits at position 'p' */
#define MASK0(n,p) (~MASK1(n,p))
/*
** the following macros help to manipulate instructions
*/
#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
#define getarg(i,pos,size) (cast(int, ((i)>>pos) & MASK1(size,0)))
#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \
((cast(Instruction, v)<<pos)&MASK1(size,pos))))
#define GETARG_A(i) getarg(i, POS_A, SIZE_A)
#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)
#define GETARG_B(i) getarg(i, POS_B, SIZE_B)
#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)
#define GETARG_C(i) getarg(i, POS_C, SIZE_C)
#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)
#define GETARG_Bx(i) getarg(i, POS_Bx, SIZE_Bx)
#define SETARG_Bx(i,v) setarg(i, v, POS_Bx, SIZE_Bx)
#define GETARG_Ax(i) getarg(i, POS_Ax, SIZE_Ax)
#define SETARG_Ax(i,v) setarg(i, v, POS_Ax, SIZE_Ax)
#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)
#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))
#define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, b)<<POS_B) \
| (cast(Instruction, c)<<POS_C))
#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, bc)<<POS_Bx))
#define CREATE_Ax(o,a) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_Ax))
/*
** Macros to operate RK indices
*/
/* this bit 1 means constant (0 means register) */
#define BITRK (1 << (SIZE_B - 1))
/* test whether value is a constant */
#define ISK(x) ((x) & BITRK)
/* gets the index of the constant */
#define INDEXK(r) ((int)(r) & ~BITRK)
#if !defined(MAXINDEXRK) /* (for debugging only) */
#define MAXINDEXRK (BITRK - 1)
#endif
/* code a constant index as a RK value */
#define RKASK(x) ((x) | BITRK)
/*
** invalid register that fits in 8 bits
*/
#define NO_REG MAXARG_A
/*
** R(x) - register
** Kst(x) - constant (in constant table)
** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
*/
/*
** grep "ORDER OP" if you change these enums
*/
typedef enum {
/*----------------------------------------------------------------------
name args description
------------------------------------------------------------------------*/
OP_MOVE,/* A B R(A) := R(B) */
OP_LOADK,/* A Bx R(A) := Kst(Bx) */
OP_LOADKX,/* A R(A) := Kst(extra arg) */
OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */
OP_GETUPVAL,/* A B R(A) := UpValue[B] */
OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */
OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */
OP_SETUPVAL,/* A B UpValue[B] := R(A) */
OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
OP_IDIV,/* A B C R(A) := RK(B) // RK(C) */
OP_BAND,/* A B C R(A) := RK(B) & RK(C) */
OP_BOR,/* A B C R(A) := RK(B) | RK(C) */
OP_BXOR,/* A B C R(A) := RK(B) ~ RK(C) */
OP_SHL,/* A B C R(A) := RK(B) << RK(C) */
OP_SHR,/* A B C R(A) := RK(B) >> RK(C) */
OP_UNM,/* A B R(A) := -R(B) */
OP_BNOT,/* A B R(A) := ~R(B) */
OP_NOT,/* A B R(A) := not R(B) */
OP_LEN,/* A B R(A) := length of R(B) */
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */
OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
OP_TEST,/* A C if not (R(A) <=> C) then pc++ */
OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */
OP_FORLOOP,/* A sBx R(A)+=R(A+2);
if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */
OP_TFORCALL,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */
OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/
OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */
OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */
OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
} OpCode;
#define NUM_OPCODES (cast(int, OP_EXTRAARG) + 1)
/*===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is
set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,
OP_SETLIST) may use 'top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0).
(*) In OP_RETURN, if (B == 0) then return up to 'top'.
(*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next
'instruction' is EXTRAARG(real C).
(*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
(*) For comparisons, A specifies what condition the test should accept
(true or false).
(*) All 'skips' (pc++) assume that next instruction is a jump.
===========================================================================*/
/*
** masks for instruction properties. The format is:
** bits 0-1: op mode
** bits 2-3: C arg mode
** bits 4-5: B arg mode
** bit 6: instruction set register A
** bit 7: operator is a test (next instruction must be a jump)
*/
enum OpArgMask {
OpArgN, /* argument is not used */
OpArgU, /* argument is used */
OpArgR, /* argument is a register or a jump offset */
OpArgK /* argument is a constant or register/constant */
};
LUAI_DDEC const lu_byte luaP_opmodes[NUM_OPCODES];
#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))
#define testAMode(m) (luaP_opmodes[m] & (1 << 6))
#define testTMode(m) (luaP_opmodes[m] & (1 << 7))
LUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */
/* number of list items to accumulate before a SETLIST instruction */
#define LFIELDS_PER_FLUSH 50
#endif
| xLua/WebGLPlugins/lopcodes.h/0 | {
"file_path": "xLua/WebGLPlugins/lopcodes.h",
"repo_id": "xLua",
"token_count": 4249
} | 2,076 |
/*
** $Id: lua.h,v 1.332 2016/12/22 15:51:20 roberto Exp $
** Lua - A Scripting Language
** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
** See Copyright Notice at the end of this file
*/
#ifndef lua_h
#define lua_h
#include <stdarg.h>
#include <stddef.h>
#include "luaconf.h"
#define LUA_VERSION_MAJOR "5"
#define LUA_VERSION_MINOR "3"
#define LUA_VERSION_NUM 503
#define LUA_VERSION_RELEASE "4"
#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2017 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
/* mark for precompiled code ('<esc>Lua') */
#define LUA_SIGNATURE "\x1bLua"
/* option for multiple returns in 'lua_pcall' and 'lua_call' */
#define LUA_MULTRET (-1)
/*
** Pseudo-indices
** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty
** space after that to help overflow detection)
*/
#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000)
#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i))
/* thread status */
#define LUA_OK 0
#define LUA_YIELD 1
#define LUA_ERRRUN 2
#define LUA_ERRSYNTAX 3
#define LUA_ERRMEM 4
#define LUA_ERRGCMM 5
#define LUA_ERRERR 6
typedef struct lua_State lua_State;
/*
** basic types
*/
#define LUA_TNONE (-1)
#define LUA_TNIL 0
#define LUA_TBOOLEAN 1
#define LUA_TLIGHTUSERDATA 2
#define LUA_TNUMBER 3
#define LUA_TSTRING 4
#define LUA_TTABLE 5
#define LUA_TFUNCTION 6
#define LUA_TUSERDATA 7
#define LUA_TTHREAD 8
#define LUA_NUMTAGS 9
/* minimum Lua stack available to a C function */
#define LUA_MINSTACK 20
/* predefined values in the registry */
#define LUA_RIDX_MAINTHREAD 1
#define LUA_RIDX_GLOBALS 2
#define LUA_RIDX_LAST LUA_RIDX_GLOBALS
/* type of numbers in Lua */
typedef LUA_NUMBER lua_Number;
/* type for integer functions */
typedef LUA_INTEGER lua_Integer;
/* unsigned integer type */
typedef LUA_UNSIGNED lua_Unsigned;
/* type for continuation-function contexts */
typedef LUA_KCONTEXT lua_KContext;
/*
** Type for C functions registered with Lua
*/
typedef int (*lua_CFunction) (lua_State *L);
/*
** Type for continuation functions
*/
typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
/*
** Type for functions that read/write blocks when loading/dumping Lua chunks
*/
typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);
/*
** Type for memory-allocation functions
*/
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
/*
** generic extra include file
*/
#if defined(LUA_USER_H)
#include LUA_USER_H
#endif
/*
** RCS ident string
*/
extern const char lua_ident[];
/*
** state manipulation
*/
LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);
LUA_API void (lua_close) (lua_State *L);
LUA_API lua_State *(lua_newthread) (lua_State *L);
LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);
LUA_API const lua_Number *(lua_version) (lua_State *L);
/*
** basic stack manipulation
*/
LUA_API int (lua_absindex) (lua_State *L, int idx);
LUA_API int (lua_gettop) (lua_State *L);
LUA_API void (lua_settop) (lua_State *L, int idx);
LUA_API void (lua_pushvalue) (lua_State *L, int idx);
LUA_API void (lua_rotate) (lua_State *L, int idx, int n);
LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx);
LUA_API int (lua_checkstack) (lua_State *L, int n);
LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n);
/*
** access functions (stack -> C)
*/
LUA_API int (lua_isnumber) (lua_State *L, int idx);
LUA_API int (lua_isstring) (lua_State *L, int idx);
LUA_API int (lua_iscfunction) (lua_State *L, int idx);
LUA_API int (lua_isinteger) (lua_State *L, int idx);
LUA_API int (lua_isuserdata) (lua_State *L, int idx);
LUA_API int (lua_type) (lua_State *L, int idx);
LUA_API const char *(lua_typename) (lua_State *L, int tp);
LUA_API lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum);
LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum);
LUA_API int (lua_toboolean) (lua_State *L, int idx);
LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
LUA_API size_t (lua_rawlen) (lua_State *L, int idx);
LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
LUA_API void *(lua_touserdata) (lua_State *L, int idx);
LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);
LUA_API const void *(lua_topointer) (lua_State *L, int idx);
/*
** Comparison and arithmetic functions
*/
#define LUA_OPADD 0 /* ORDER TM, ORDER OP */
#define LUA_OPSUB 1
#define LUA_OPMUL 2
#define LUA_OPMOD 3
#define LUA_OPPOW 4
#define LUA_OPDIV 5
#define LUA_OPIDIV 6
#define LUA_OPBAND 7
#define LUA_OPBOR 8
#define LUA_OPBXOR 9
#define LUA_OPSHL 10
#define LUA_OPSHR 11
#define LUA_OPUNM 12
#define LUA_OPBNOT 13
LUA_API void (lua_arith) (lua_State *L, int op);
#define LUA_OPEQ 0
#define LUA_OPLT 1
#define LUA_OPLE 2
LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);
LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op);
/*
** push functions (C -> stack)
*/
LUA_API void (lua_pushnil) (lua_State *L);
LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);
LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);
LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);
LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
va_list argp);
LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);
LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
LUA_API void (lua_pushboolean) (lua_State *L, int b);
LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p);
LUA_API int (lua_pushthread) (lua_State *L);
/*
** get functions (Lua -> stack)
*/
LUA_API int (lua_getglobal) (lua_State *L, const char *name);
LUA_API int (lua_gettable) (lua_State *L, int idx);
LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);
LUA_API int (lua_rawget) (lua_State *L, int idx);
LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
LUA_API int (lua_getuservalue) (lua_State *L, int idx);
/*
** set functions (stack -> Lua)
*/
LUA_API void (lua_setglobal) (lua_State *L, const char *name);
LUA_API void (lua_settable) (lua_State *L, int idx);
LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k);
LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n);
LUA_API void (lua_rawset) (lua_State *L, int idx);
LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);
LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
LUA_API void (lua_setuservalue) (lua_State *L, int idx);
/*
** 'load' and 'call' functions (load and run Lua code)
*/
LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults,
lua_KContext ctx, lua_KFunction k);
#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL)
LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
lua_KContext ctx, lua_KFunction k);
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
const char *chunkname, const char *mode);
LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
/*
** coroutine functions
*/
LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx,
lua_KFunction k);
LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);
LUA_API int (lua_status) (lua_State *L);
LUA_API int (lua_isyieldable) (lua_State *L);
#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)
/*
** garbage-collection function and options
*/
#define LUA_GCSTOP 0
#define LUA_GCRESTART 1
#define LUA_GCCOLLECT 2
#define LUA_GCCOUNT 3
#define LUA_GCCOUNTB 4
#define LUA_GCSTEP 5
#define LUA_GCSETPAUSE 6
#define LUA_GCSETSTEPMUL 7
#define LUA_GCISRUNNING 9
LUA_API int (lua_gc) (lua_State *L, int what, int data);
/*
** miscellaneous functions
*/
LUA_API int (lua_error) (lua_State *L);
LUA_API int (lua_next) (lua_State *L, int idx);
LUA_API void (lua_concat) (lua_State *L, int n);
LUA_API void (lua_len) (lua_State *L, int idx);
LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s);
LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
/*
** {==============================================================
** some useful macros
** ===============================================================
*/
#define lua_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE))
#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL)
#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL)
#define lua_pop(L,n) lua_settop(L, -(n)-1)
#define lua_newtable(L) lua_createtable(L, 0, 0)
#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)
#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)
#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA)
#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL)
#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN)
#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD)
#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE)
#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0)
#define lua_pushliteral(L, s) lua_pushstring(L, "" s)
#define lua_pushglobaltable(L) \
((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS))
#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
#define lua_insert(L,idx) lua_rotate(L, (idx), 1)
#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1))
#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1))
/* }============================================================== */
/*
** {==============================================================
** compatibility macros for unsigned conversions
** ===============================================================
*/
#if defined(LUA_COMPAT_APIINTCASTS)
#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is))
#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL)
#endif
/* }============================================================== */
/*
** {======================================================================
** Debug API
** =======================================================================
*/
/*
** Event codes
*/
#define LUA_HOOKCALL 0
#define LUA_HOOKRET 1
#define LUA_HOOKLINE 2
#define LUA_HOOKCOUNT 3
#define LUA_HOOKTAILCALL 4
/*
** Event masks
*/
#define LUA_MASKCALL (1 << LUA_HOOKCALL)
#define LUA_MASKRET (1 << LUA_HOOKRET)
#define LUA_MASKLINE (1 << LUA_HOOKLINE)
#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)
typedef struct lua_Debug lua_Debug; /* activation record */
/* Functions to be called by the debugger in specific events */
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
LUA_API int (lua_getstack) (lua_State *L, int level, lua_Debug *ar);
LUA_API int (lua_getinfo) (lua_State *L, const char *what, lua_Debug *ar);
LUA_API const char *(lua_getlocal) (lua_State *L, const lua_Debug *ar, int n);
LUA_API const char *(lua_setlocal) (lua_State *L, const lua_Debug *ar, int n);
LUA_API const char *(lua_getupvalue) (lua_State *L, int funcindex, int n);
LUA_API const char *(lua_setupvalue) (lua_State *L, int funcindex, int n);
LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n);
LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
int fidx2, int n2);
LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
LUA_API lua_Hook (lua_gethook) (lua_State *L);
LUA_API int (lua_gethookmask) (lua_State *L);
LUA_API int (lua_gethookcount) (lua_State *L);
struct lua_Debug {
int event;
const char *name; /* (n) */
const char *namewhat; /* (n) 'global', 'local', 'field', 'method' */
const char *what; /* (S) 'Lua', 'C', 'main', 'tail' */
const char *source; /* (S) */
int currentline; /* (l) */
int linedefined; /* (S) */
int lastlinedefined; /* (S) */
unsigned char nups; /* (u) number of upvalues */
unsigned char nparams;/* (u) number of parameters */
char isvararg; /* (u) */
char istailcall; /* (t) */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */
struct CallInfo *i_ci; /* active function */
};
/* }====================================================================== */
/******************************************************************************
* Copyright (C) 1994-2017 Lua.org, PUC-Rio.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
#endif
| xLua/WebGLPlugins/lua.h/0 | {
"file_path": "xLua/WebGLPlugins/lua.h",
"repo_id": "xLua",
"token_count": 6238
} | 2,077 |
cmake_minimum_required(VERSION 3.6)
macro(Highlight_Error error_msg)
message("==================")
message("Error: ${error_msg}")
message("==================")
message(FATAL_ERROR "")
endmacro()
if(NOT DEFINED ENV{ANDROID_NDK})
Highlight_Error("not defined environment variable %ANDROID_NDK%")
else()
set(ANDROID_NDK $ENV{ANDROID_NDK})
endif()
file(TO_CMAKE_PATH "${ANDROID_NDK}" ANDROID_NDK)
if(ANDROID_TOOLCHAIN_NAME AND NOT ANDROID_TOOLCHAIN)
if(ANDROID_TOOLCHAIN_NAME MATCHES "-clang([0-9].[0-9])?$")
set(ANDROID_TOOLCHAIN clang)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "-[0-9].[0-9]$")
set(ANDROID_TOOLCHAIN gcc)
endif()
endif()
if(ANDROID_ABI STREQUAL "armeabi-v7a with NEON")
set(ANDROID_ABI armeabi-v7a)
set(ANDROID_ARM_NEON TRUE)
elseif(ANDROID_TOOLCHAIN_NAME AND NOT ANDROID_ABI)
if(ANDROID_TOOLCHAIN_NAME MATCHES "^arm-linux-androideabi-")
set(ANDROID_ABI armeabi-v7a)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "^aarch64-linux-android-")
set(ANDROID_ABI arm64-v8a)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "^x86-")
set(ANDROID_ABI x86)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "^x86_64-")
set(ANDROID_ABI x86_64)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "^mipsel-linux-android-")
set(ANDROID_ABI mips)
elseif(ANDROID_TOOLCHAIN_NAME MATCHES "^mips64el-linux-android-")
set(ANDROID_ABI mips64)
endif()
endif()
if(ANDROID_NATIVE_API_LEVEL AND NOT ANDROID_PLATFORM)
if(ANDROID_NATIVE_API_LEVEL MATCHES "^android-[0-9]+$")
set(ANDROID_PLATFORM ${ANDROID_NATIVE_API_LEVEL})
elseif(ANDROID_NATIVE_API_LEVEL MATCHES "^[0-9]+$")
set(ANDROID_PLATFORM android-${ANDROID_NATIVE_API_LEVEL})
endif()
endif()
if(DEFINED ANDROID_APP_PIE AND NOT DEFINED ANDROID_PIE)
set(ANDROID_PIE "${ANDROID_APP_PIE}")
endif()
if(ANDROID_STL_FORCE_FEATURES AND NOT DEFINED ANDROID_CPP_FEATURES)
set(ANDROID_CPP_FEATURES "rtti exceptions")
endif()
if(DEFINED ANDROID_NO_UNDEFINED AND NOT DEFINED ANDROID_ALLOW_UNDEFINED_SYMBOLS)
if(ANDROID_NO_UNDEFINED)
set(ANDROID_ALLOW_UNDEFINED_SYMBOLS FALSE)
else()
set(ANDROID_ALLOW_UNDEFINED_SYMBOLS TRUE)
endif()
endif()
if(DEFINED ANDROID_SO_UNDEFINED AND NOT DEFINED ANDROID_ALLOW_UNDEFINED_SYMBOLS)
set(ANDROID_ALLOW_UNDEFINED_SYMBOLS "${ANDROID_SO_UNDEFINED}")
endif()
if(DEFINED ANDROID_FORCE_ARM_BUILD AND NOT ANDROID_ARM_MODE)
if(ANDROID_FORCE_ARM_BUILD)
set(ANDROID_ARM_MODE arm)
else()
set(ANDROID_ARM_MODE thumb)
endif()
endif()
if(DEFINED ANDROID_NOEXECSTACK AND NOT DEFINED ANDROID_DISABLE_NO_EXECUTE)
if(ANDROID_NOEXECSTACK)
set(ANDROID_DISABLE_NO_EXECUTE FALSE)
else()
set(ANDROID_DISABLE_NO_EXECUTE TRUE)
endif()
endif()
if(DEFINED ANDROID_RELRO AND NOT DEFINED ANDROID_DISABLE_RELRO)
if(ANDROID_RELRO)
set(ANDROID_DISABLE_RELRO FALSE)
else()
set(ANDROID_DISABLE_RELRO TRUE)
endif()
endif()
if(NDK_CCACHE AND NOT ANDROID_CCACHE)
set(ANDROID_CCACHE "${NDK_CCACHE}")
endif()
# Default values for configurable variables.
if(NOT ANDROID_TOOLCHAIN)
set(ANDROID_TOOLCHAIN clang)
endif()
if(NOT ANDROID_ABI)
set(ANDROID_ABI armeabi-v7a)
endif()
if(ANDROID_PLATFORM MATCHES "^android-([0-8]|10|11)$")
set(ANDROID_PLATFORM android-9)
elseif(ANDROID_PLATFORM STREQUAL android-20)
set(ANDROID_PLATFORM android-19)
elseif(NOT ANDROID_PLATFORM)
set(ANDROID_PLATFORM android-9)
endif()
string(REPLACE "android-" "" ANDROID_PLATFORM_LEVEL ${ANDROID_PLATFORM})
if(ANDROID_ABI MATCHES "64(-v8a)?$" AND ANDROID_PLATFORM_LEVEL LESS 21)
set(ANDROID_PLATFORM android-21)
set(ANDROID_PLATFORM_LEVEL 21)
endif()
if(NOT ANDROID_STL)
set(ANDROID_STL gnustl_static)
endif()
if(NOT DEFINED ANDROID_PIE)
if(ANDROID_PLATFORM_LEVEL LESS 16)
set(ANDROID_PIE FALSE)
else()
set(ANDROID_PIE TRUE)
endif()
endif()
if(NOT ANDROID_ARM_MODE)
set(ANDROID_ARM_MODE thumb)
endif()
# Export configurable variables for the try_compile() command.
set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES
ANDROID_TOOLCHAIN
ANDROID_ABI
ANDROID_PLATFORM
ANDROID_STL
ANDROID_PIE
ANDROID_CPP_FEATURES
ANDROID_ALLOW_UNDEFINED_SYMBOLS
ANDROID_ARM_MODE
ANDROID_ARM_NEON
ANDROID_DISABLE_NO_EXECUTE
ANDROID_DISABLE_RELRO
ANDROID_DISABLE_FORMAT_STRING_CHECKS
ANDROID_CCACHE)
# Standard cross-compiling stuff.
set(ANDROID TRUE)
set(CMAKE_SYSTEM_NAME Android)
set(CMAKE_SYSTEM_VERSION ${ANDROID_PLATFORM_LEVEL})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
# ABI.
set(CMAKE_ANDROID_ARCH_ABI ${ANDROID_ABI})
if(ANDROID_ABI MATCHES "^armeabi(-v7a)?$")
set(ANDROID_SYSROOT_ABI arm)
set(ANDROID_TOOLCHAIN_NAME arm-linux-androideabi)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_TOOLCHAIN_NAME})
if(ANDROID_ABI STREQUAL armeabi)
set(CMAKE_SYSTEM_PROCESSOR armv5te)
set(ANDROID_LLVM_TRIPLE armv5te-none-linux-androideabi)
elseif(ANDROID_ABI STREQUAL armeabi-v7a)
set(CMAKE_SYSTEM_PROCESSOR armv7-a)
set(ANDROID_LLVM_TRIPLE armv7-none-linux-androideabi)
endif()
elseif(ANDROID_ABI STREQUAL arm64-v8a)
set(ANDROID_SYSROOT_ABI arm64)
set(CMAKE_SYSTEM_PROCESSOR aarch64)
set(ANDROID_TOOLCHAIN_NAME aarch64-linux-android)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_TOOLCHAIN_NAME})
set(ANDROID_LLVM_TRIPLE aarch64-none-linux-android)
elseif(ANDROID_ABI STREQUAL x86)
set(ANDROID_SYSROOT_ABI x86)
set(CMAKE_SYSTEM_PROCESSOR i686)
set(ANDROID_TOOLCHAIN_NAME i686-linux-android)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_ABI})
set(ANDROID_LLVM_TRIPLE i686-none-linux-android)
elseif(ANDROID_ABI STREQUAL x86_64)
set(ANDROID_SYSROOT_ABI x86_64)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(ANDROID_TOOLCHAIN_NAME x86_64-linux-android)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_ABI})
set(ANDROID_LLVM_TRIPLE x86_64-none-linux-android)
elseif(ANDROID_ABI STREQUAL mips)
set(ANDROID_SYSROOT_ABI mips)
set(CMAKE_SYSTEM_PROCESSOR mips)
set(ANDROID_TOOLCHAIN_NAME mipsel-linux-android)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_TOOLCHAIN_NAME})
set(ANDROID_LLVM_TRIPLE mipsel-none-linux-android)
elseif(ANDROID_ABI STREQUAL mips64)
set(ANDROID_SYSROOT_ABI mips64)
set(CMAKE_SYSTEM_PROCESSOR mips64)
set(ANDROID_TOOLCHAIN_NAME mips64el-linux-android)
set(ANDROID_TOOLCHAIN_ROOT ${ANDROID_TOOLCHAIN_NAME})
set(ANDROID_LLVM_TRIPLE mips64el-none-linux-android)
else()
message(FATAL_ERROR "Invalid Android ABI: ${ANDROID_ABI}.")
endif()
# STL.
set(ANDROID_STL_STATIC_LIBRARIES)
set(ANDROID_STL_SHARED_LIBRARIES)
if(ANDROID_STL STREQUAL system)
set(ANDROID_STL_STATIC_LIBRARIES
supc++)
elseif(ANDROID_STL STREQUAL stlport_static)
set(ANDROID_STL_STATIC_LIBRARIES
stlport_static)
elseif(ANDROID_STL STREQUAL stlport_shared)
set(ANDROID_STL_SHARED_LIBRARIES
stlport_shared)
elseif(ANDROID_STL STREQUAL gnustl_static)
set(ANDROID_STL_STATIC_LIBRARIES
gnustl_static)
elseif(ANDROID_STL STREQUAL gnustl_shared)
set(ANDROID_STL_STATIC_LIBRARIES
supc++)
set(ANDROID_STL_SHARED_LIBRARIES
gnustl_shared)
elseif(ANDROID_STL STREQUAL c++_static)
set(ANDROID_STL_STATIC_LIBRARIES
c++_static
c++abi
unwind
android_support)
elseif(ANDROID_STL STREQUAL c++_shared)
set(ANDROID_STL_STATIC_LIBRARIES
unwind)
set(ANDROID_STL_SHARED_LIBRARIES
c++_shared)
elseif(ANDROID_STL STREQUAL none)
else()
message(FATAL_ERROR "Invalid Android STL: ${ANDROID_STL}.")
endif()
# Sysroot.
set(CMAKE_SYSROOT "${ANDROID_NDK}/platforms/${ANDROID_PLATFORM}/arch-${ANDROID_SYSROOT_ABI}")
# Toolchain.
if(CMAKE_HOST_SYSTEM_NAME STREQUAL Linux)
set(ANDROID_HOST_TAG linux-x86_64)
elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL Darwin)
set(ANDROID_HOST_TAG darwin-x86_64)
elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL Windows)
set(ANDROID_HOST_TAG windows-x86_64)
endif()
set(ANDROID_TOOLCHAIN_ROOT "${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_ROOT}-4.9/prebuilt/${ANDROID_HOST_TAG}")
set(ANDROID_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_NAME}-")
if(CMAKE_HOST_SYSTEM_NAME STREQUAL Windows)
set(ANDROID_TOOLCHAIN_SUFFIX .exe)
endif()
if(ANDROID_TOOLCHAIN STREQUAL clang)
set(ANDROID_LLVM_TOOLCHAIN_PREFIX "${ANDROID_NDK}/toolchains/llvm-3.6/prebuilt/${ANDROID_HOST_TAG}/bin/")
set(ANDROID_C_COMPILER "${ANDROID_LLVM_TOOLCHAIN_PREFIX}clang${ANDROID_TOOLCHAIN_SUFFIX}")
set(ANDROID_CXX_COMPILER "${ANDROID_LLVM_TOOLCHAIN_PREFIX}clang++${ANDROID_TOOLCHAIN_SUFFIX}")
# Clang can fail to compile if CMake doesn't correctly supply the target and
# external toolchain, but to do so, CMake needs to already know that the
# compiler is clang. Tell CMake that the compiler is really clang, but don't
# use CMakeForceCompiler, since we still want compile checks. We only want
# to skip the compiler ID detection step.
set(CMAKE_C_COMPILER_ID_RUN TRUE)
set(CMAKE_CXX_COMPILER_ID_RUN TRUE)
set(CMAKE_C_COMPILER_ID Clang)
set(CMAKE_CXX_COMPILER_ID Clang)
set(CMAKE_C_COMPILER_TARGET ${ANDROID_LLVM_TRIPLE})
set(CMAKE_CXX_COMPILER_TARGET ${ANDROID_LLVM_TRIPLE})
set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN "${ANDROID_TOOLCHAIN_ROOT}")
set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${ANDROID_TOOLCHAIN_ROOT}")
elseif(ANDROID_TOOLCHAIN STREQUAL gcc)
set(ANDROID_C_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}gcc${ANDROID_TOOLCHAIN_SUFFIX}")
set(ANDROID_CXX_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}g++${ANDROID_TOOLCHAIN_SUFFIX}")
else()
message(FATAL_ERROR "Invalid Android toolchain: ${ANDROID_TOOLCHAIN}.")
endif()
if(NOT IS_DIRECTORY "${ANDROID_NDK}/platforms/${ANDROID_PLATFORM}")
message("${ANDROID_NDK}/platforms/${ANDROID_PLATFORM}")
message(FATAL_ERROR "Invalid Android platform: ${ANDROID_PLATFORM}.")
elseif(NOT IS_DIRECTORY "${CMAKE_SYSROOT}")
message(FATAL_ERROR "Invalid Android sysroot: ${CMAKE_SYSROOT}.")
endif()
set(ANDROID_COMPILER_FLAGS)
set(ANDROID_COMPILER_FLAGS_CXX)
set(ANDROID_COMPILER_FLAGS_DEBUG)
set(ANDROID_COMPILER_FLAGS_RELEASE)
set(ANDROID_LINKER_FLAGS)
set(ANDROID_LINKER_FLAGS_EXE)
# Generic flags.
list(APPEND ANDROID_COMPILER_FLAGS
-g
-DANDROID
-ffunction-sections
-funwind-tables
-fstack-protector-strong
-no-canonical-prefixes)
list(APPEND ANDROID_COMPILER_FLAGS_CXX
-fno-exceptions
-fno-rtti)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,--build-id
-Wl,--warn-shared-textrel
-Wl,--fatal-warnings)
list(APPEND ANDROID_LINKER_FLAGS_EXE
-Wl,--gc-sections
-Wl,-z,nocopyreloc)
# Debug and release flags.
list(APPEND ANDROID_COMPILER_FLAGS_DEBUG
-O0)
if(ANDROID_ABI MATCHES "^armeabi")
list(APPEND ANDROID_COMPILER_FLAGS_RELEASE
-Os)
else()
list(APPEND ANDROID_COMPILER_FLAGS_RELEASE
-O2)
endif()
list(APPEND ANDROID_COMPILER_FLAGS_RELEASE
-DNDEBUG)
if(ANDROID_TOOLCHAIN STREQUAL clang)
list(APPEND ANDROID_COMPILER_FLAGS_DEBUG
-fno-limit-debug-info)
endif()
# Toolchain and ABI specific flags.
if(ANDROID_ABI STREQUAL armeabi)
list(APPEND ANDROID_COMPILER_FLAGS
-march=armv5te
-mtune=xscale
-msoft-float)
endif()
if(ANDROID_ABI STREQUAL armeabi-v7a)
list(APPEND ANDROID_COMPILER_FLAGS
-march=armv7-a
-mfloat-abi=softfp
-mfpu=vfpv3-d16)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,--fix-cortex-a8)
endif()
if(ANDROID_ABI MATCHES "^armeabi" AND ANDROID_TOOLCHAIN STREQUAL clang)
# Disable integrated-as for better compatibility.
list(APPEND ANDROID_COMPILER_FLAGS
-fno-integrated-as)
endif()
if(ANDROID_ABI STREQUAL mips AND ANDROID_TOOLCHAIN STREQUAL clang)
list(APPEND ANDROID_COMPILER_FLAGS
-mips32)
endif()
# STL specific flags.
if(ANDROID_STL STREQUAL system)
set(ANDROID_STL_PREFIX gnu-libstdc++/4.9)
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
"${ANDROID_NDK}/sources/cxx-stl/system/include")
elseif(ANDROID_STL MATCHES "^stlport_")
set(ANDROID_STL_PREFIX stlport)
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/stlport"
"${ANDROID_NDK}/sources/cxx-stl/gabi++/include")
elseif(ANDROID_STL MATCHES "^gnustl_")
set(ANDROID_STL_PREFIX gnu-libstdc++/4.9)
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/include"
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/libs/${ANDROID_ABI}/include"
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/include/backward")
elseif(ANDROID_STL MATCHES "^c\\+\\+_")
set(ANDROID_STL_PREFIX llvm-libc++)
if(ANDROID_ABI MATCHES "^armeabi")
list(APPEND ANDROID_LINKER_FLAGS
-Wl,--exclude-libs,libunwind.a)
else()
list(REMOVE_ITEM ANDROID_STL_STATIC_LIBRARIES
unwind)
endif()
list(APPEND ANDROID_COMPILER_FLAGS_CXX
-std=c++11)
if(ANDROID_TOOLCHAIN STREQUAL gcc)
list(APPEND ANDROID_COMPILER_FLAGS_CXX
-fno-strict-aliasing)
endif()
set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/include"
"${ANDROID_NDK}/sources/android/support/include"
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}abi/include")
endif()
set(ANDROID_CXX_STANDARD_LIBRARIES)
foreach(library ${ANDROID_STL_STATIC_LIBRARIES})
list(APPEND ANDROID_CXX_STANDARD_LIBRARIES
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/libs/${ANDROID_ABI}/lib${library}.a")
endforeach()
foreach(library ${ANDROID_STL_SHARED_LIBRARIES})
list(APPEND ANDROID_CXX_STANDARD_LIBRARIES
"${ANDROID_NDK}/sources/cxx-stl/${ANDROID_STL_PREFIX}/libs/${ANDROID_ABI}/lib${library}.so")
endforeach()
if(ANDROID_ABI STREQUAL armeabi AND NOT ANDROID_STL MATCHES "^(none|system)$")
list(APPEND ANDROID_CXX_STANDARD_LIBRARIES
-latomic)
endif()
set(CMAKE_C_STANDARD_LIBRARIES_INIT "-lm")
set(CMAKE_CXX_STANDARD_LIBRARIES_INIT "${CMAKE_C_STANDARD_LIBRARIES_INIT}")
if(ANDROID_CXX_STANDARD_LIBRARIES)
string(REPLACE ";" "\" \"" ANDROID_CXX_STANDARD_LIBRARIES "\"${ANDROID_CXX_STANDARD_LIBRARIES}\"")
set(CMAKE_CXX_STANDARD_LIBRARIES_INIT "${CMAKE_CXX_STANDARD_LIBRARIES_INIT} ${ANDROID_CXX_STANDARD_LIBRARIES}")
endif()
# Configuration specific flags.
if(ANDROID_PIE)
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)
list(APPEND ANDROID_LINKER_FLAGS_EXE
-pie
-fPIE)
endif()
if(ANDROID_CPP_FEATURES)
separate_arguments(ANDROID_CPP_FEATURES)
foreach(feature ${ANDROID_CPP_FEATURES})
if(NOT ${feature} MATCHES "^(rtti|exceptions)$")
message(FATAL_ERROR "Invalid Android C++ feature: ${feature}.")
endif()
list(APPEND ANDROID_COMPILER_FLAGS_CXX
-f${feature})
endforeach()
string(REPLACE ";" " " ANDROID_CPP_FEATURES "${ANDROID_CPP_FEATURES}")
endif()
if(NOT ANDROID_ALLOW_UNDEFINED_SYMBOLS)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,--no-undefined)
endif()
if(ANDROID_ABI MATCHES "armeabi")
if(ANDROID_ARM_MODE STREQUAL thumb)
list(APPEND ANDROID_COMPILER_FLAGS
-mthumb)
elseif(ANDROID_ARM_MODE STREQUAL arm)
list(APPEND ANDROID_COMPILER_FLAGS
-marm)
else()
message(FATAL_ERROR "Invalid Android ARM mode: ${ANDROID_ARM_MODE}.")
endif()
if(ANDROID_ABI STREQUAL armeabi-v7a AND ANDROID_ARM_NEON)
list(APPEND ANDROID_COMPILER_FLAGS
-mfpu=neon)
endif()
endif()
if(ANDROID_DISABLE_NO_EXECUTE)
list(APPEND ANDROID_COMPILER_FLAGS
-Wa,--execstack)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,-z,execstack)
else()
list(APPEND ANDROID_COMPILER_FLAGS
-Wa,--noexecstack)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,-z,noexecstack)
endif()
if(ANDROID_TOOLCHAIN STREQUAL clang)
# CMake automatically forwards all compiler flags to the linker,
# and clang doesn't like having -Wa flags being used for linking.
# To prevent CMake from doing this would require meddling with
# the CMAKE_<LANG>_COMPILE_OBJECT rules, which would get quite messy.
list(APPEND ANDROID_LINKER_FLAGS
-Qunused-arguments)
endif()
if(ANDROID_DISABLE_RELRO)
list(APPEND ANDROID_LINKER_FLAGS
-Wl,-z,norelro -Wl,-z,lazy)
else()
list(APPEND ANDROID_LINKER_FLAGS
-Wl,-z,relro -Wl,-z,now)
endif()
if(ANDROID_DISABLE_FORMAT_STRING_CHECKS)
list(APPEND ANDROID_COMPILER_FLAGS
-Wno-error=format-security)
else()
list(APPEND ANDROID_COMPILER_FLAGS
-Wformat -Werror=format-security)
endif()
# Convert these lists into strings.
string(REPLACE ";" " " ANDROID_COMPILER_FLAGS "${ANDROID_COMPILER_FLAGS}")
string(REPLACE ";" " " ANDROID_COMPILER_FLAGS_CXX "${ANDROID_COMPILER_FLAGS_CXX}")
string(REPLACE ";" " " ANDROID_COMPILER_FLAGS_DEBUG "${ANDROID_COMPILER_FLAGS_DEBUG}")
string(REPLACE ";" " " ANDROID_COMPILER_FLAGS_RELEASE "${ANDROID_COMPILER_FLAGS_RELEASE}")
string(REPLACE ";" " " ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}")
string(REPLACE ";" " " ANDROID_LINKER_FLAGS_EXE "${ANDROID_LINKER_FLAGS_EXE}")
if(ANDROID_CCACHE)
set(CMAKE_C_COMPILER_LAUNCHER "${ANDROID_CCACHE}")
set(CMAKE_CXX_COMPILER_LAUNCHER "${ANDROID_CCACHE}")
endif()
set(CMAKE_C_COMPILER "${ANDROID_C_COMPILER}")
set(CMAKE_CXX_COMPILER "${ANDROID_CXX_COMPILER}")
set(_CMAKE_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_PREFIX}")
# Set or retrieve the cached flags.
# This is necessary in case the user sets/changes flags in subsequent
# configures. If we included the Android flags in here, they would get
# overwritten.
set(CMAKE_C_FLAGS ""
CACHE STRING "Flags used by the compiler during all build types.")
set(CMAKE_CXX_FLAGS ""
CACHE STRING "Flags used by the compiler during all build types.")
set(CMAKE_C_FLAGS_DEBUG ""
CACHE STRING "Flags used by the compiler during debug builds.")
set(CMAKE_CXX_FLAGS_DEBUG ""
CACHE STRING "Flags used by the compiler during debug builds.")
set(CMAKE_C_FLAGS_RELEASE ""
CACHE STRING "Flags used by the compiler during release builds.")
set(CMAKE_CXX_FLAGS_RELEASE ""
CACHE STRING "Flags used by the compiler during release builds.")
set(CMAKE_MODULE_LINKER_FLAGS ""
CACHE STRING "Flags used by the linker during the creation of modules.")
set(CMAKE_SHARED_LINKER_FLAGS ""
CACHE STRING "Flags used by the linker during the creation of dll's.")
set(CMAKE_EXE_LINKER_FLAGS ""
CACHE STRING "Flags used by the linker.")
set(CMAKE_C_FLAGS "${ANDROID_COMPILER_FLAGS} ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "${ANDROID_COMPILER_FLAGS} ${ANDROID_COMPILER_FLAGS_CXX} ${CMAKE_CXX_FLAGS}")
set(CMAKE_C_FLAGS_DEBUG "${ANDROID_COMPILER_FLAGS_DEBUG} ${CMAKE_C_FLAGS_DEBUG}")
set(CMAKE_CXX_FLAGS_DEBUG "${ANDROID_COMPILER_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_DEBUG}")
set(CMAKE_C_FLAGS_RELEASE "${ANDROID_COMPILER_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_RELEASE "${ANDROID_COMPILER_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
set(CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${ANDROID_LINKER_FLAGS_EXE} ${CMAKE_EXE_LINKER_FLAGS}")
if(CMAKE_C_FLAGS)
message("CMAKE_C_FLAGS = ${CMAKE_C_FlAGS}")
endif()
if(CMAKE_CXX_FLAGS)
message("CMAKE_CXX_FLAGS = ${CMAKE_CXX_FLAGS}")
endif()
if(CMAKE_C_FLAGS_DEBUG)
message("CMAKE_C_FLAGS_DEBUG = ${CMAKE_C_FLAGS_DEBUG}")
endif()
if(CMAKE_CXX_FLAGS_DEBUG)
message("CMAKE_CXX_FLAGS_DEBUG = ${CMAKE_CXX_FLAGS_DEBUG}")
endif()
if(CMAKE_SHARED_LINKER_FLAGS)
message("CMAKE_SHARED_LINKDER_FLAGS = ${CMAKE_SHARED_LINKER_FLAGS}")
endif()
if(CMAKE_MODULE_LINKER_FLAGS)
message("CMAKE_MODULE_LINKER_FLAGS = ${CMAKE_MODULE_LINKER_FLAGS}")
endif()
if(CMAKE_EXE_LINKER_FLAGS)
message("CMAKE_EXE_LINKER_FLAGS = ${CMAKE_EXE_LINKER_FLAGS}")
endif()
# Compatibility for read-only variables.
# Read-only variables for compatibility with the other toolchain file.
# We'll keep these around for the existing projects that still use them.
# TODO: All of the variables here have equivalents in our standard set of
# configurable variables, so we can remove these once most of our users migrate
# to those variables.
set(ANDROID_NATIVE_API_LEVEL ${ANDROID_PLATFORM_LEVEL})
if(ANDROID_ALLOW_UNDEFINED_SYMBOLS)
set(ANDROID_SO_UNDEFINED TRUE)
else()
set(ANDROID_NO_UNDEFINED TRUE)
endif()
set(ANDROID_FUNCTION_LEVEL_LINKING TRUE)
set(ANDROID_GOLD_LINKER TRUE)
if(NOT ANDROID_DISABLE_NO_EXECUTE)
set(ANDROID_NOEXECSTACK TRUE)
endif()
if(NOT ANDROID_DISABLE_RELRO)
set(ANDROID_RELRO TRUE)
endif()
if(ANDROID_ARM_MODE STREQUAL arm)
set(ANDROID_FORCE_ARM_BUILD TRUE)
endif()
if(ANDROID_CPP_FEATURES MATCHES "rtti"
AND ANDROID_CPP_FEATURES MATCHES "exceptions")
set(ANDROID_STL_FORCE_FEATURES TRUE)
endif()
if(ANDROID_CCACHE)
set(NDK_CCACHE "${ANDROID_CCACHE}")
endif()
if(ANDROID_TOOLCHAIN STREQUAL clang)
set(ANDROID_TOOLCHAIN_NAME ${ANDROID_TOOLCHAIN_NAME}-clang)
else()
set(ANDROID_TOOLCHAIN_NAME ${ANDROID_TOOLCHAIN_NAME}-4.9)
endif()
set(ANDROID_NDK_HOST_X64 TRUE)
set(ANDROID_NDK_LAYOUT RELEASE)
if(ANDROID_ABI STREQUAL armeabi)
set(ARMEABI TRUE)
elseif(ANDROID_ABI STREQUAL armeabi-v7a)
set(ARMEABI_V7A TRUE)
if(ANDROID_ARM_NEON)
set(NEON TRUE)
endif()
elseif(ANDROID_ABI STREQUAL arm64-v8a)
set(ARM64_V8A TRUE)
elseif(ANDROID_ABI STREQUAL x86)
set(X86 TRUE)
elseif(ANDROID_ABI STREQUAL x86_64)
set(X86_64 TRUE)
elseif(ANDROID_ABI STREQUAL mips)
set(MIPS TRUE)
elseif(ANDROID_ABI STREQUAL MIPS64)
set(MIPS64 TRUE)
endif()
set(ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_HOST_TAG})
set(ANDROID_NDK_ABI_NAME ${ANDROID_ABI})
set(ANDROID_ARCH_NAME ${ANDROID_SYSROOT_ABI})
set(ANDROID_SYSROOT "${CMAKE_SYSROOT}")
set(TOOL_OS_SUFFIX ${ANDROID_TOOLCHAIN_SUFFIX})
if(ANDROID_TOOLCHAIN STREQUAL clang)
set(ANDROID_COMPILER_IS_CLANG TRUE)
endif()
| xLua/build/cmake/android.windows.toolchain.cmake/0 | {
"file_path": "xLua/build/cmake/android.windows.toolchain.cmake",
"repo_id": "xLua",
"token_count": 10103
} | 2,078 |
.\" $Id: luac.man,v 1.28 2006/01/06 16:03:34 lhf Exp $
.TH LUAC 1 "$Date: 2006/01/06 16:03:34 $"
.SH NAME
luac \- Lua compiler
.SH SYNOPSIS
.B luac
[
.I options
] [
.I filenames
]
.SH DESCRIPTION
.B luac
is the Lua compiler.
It translates programs written in the Lua programming language
into binary files that can be later loaded and executed.
.LP
The main advantages of precompiling chunks are:
faster loading,
protecting source code from accidental user changes,
and
off-line syntax checking.
.LP
Pre-compiling does not imply faster execution
because in Lua chunks are always compiled into bytecodes before being executed.
.B luac
simply allows those bytecodes to be saved in a file for later execution.
.LP
Pre-compiled chunks are not necessarily smaller than the corresponding source.
The main goal in pre-compiling is faster loading.
.LP
The binary files created by
.B luac
are portable only among architectures with the same word size and byte order.
.LP
.B luac
produces a single output file containing the bytecodes
for all source files given.
By default,
the output file is named
.BR luac.out ,
but you can change this with the
.B \-o
option.
.LP
In the command line,
you can mix
text files containing Lua source and
binary files containing precompiled chunks.
This is useful to combine several precompiled chunks,
even from different (but compatible) platforms,
into a single precompiled chunk.
.LP
You can use
.B "'\-'"
to indicate the standard input as a source file
and
.B "'\--'"
to signal the end of options
(that is,
all remaining arguments will be treated as files even if they start with
.BR "'\-'" ).
.LP
The internal format of the binary files produced by
.B luac
is likely to change when a new version of Lua is released.
So,
save the source files of all Lua programs that you precompile.
.LP
.SH OPTIONS
Options must be separate.
.TP
.B \-l
produce a listing of the compiled bytecode for Lua's virtual machine.
Listing bytecodes is useful to learn about Lua's virtual machine.
If no files are given, then
.B luac
loads
.B luac.out
and lists its contents.
.TP
.BI \-o " file"
output to
.IR file ,
instead of the default
.BR luac.out .
(You can use
.B "'\-'"
for standard output,
but not on platforms that open standard output in text mode.)
The output file may be a source file because
all files are loaded before the output file is written.
Be careful not to overwrite precious files.
.TP
.B \-p
load files but do not generate any output file.
Used mainly for syntax checking and for testing precompiled chunks:
corrupted files will probably generate errors when loaded.
Lua always performs a thorough integrity test on precompiled chunks.
Bytecode that passes this test is completely safe,
in the sense that it will not break the interpreter.
However,
there is no guarantee that such code does anything sensible.
(None can be given, because the halting problem is unsolvable.)
If no files are given, then
.B luac
loads
.B luac.out
and tests its contents.
No messages are displayed if the file passes the integrity test.
.TP
.B \-s
strip debug information before writing the output file.
This saves some space in very large chunks,
but if errors occur when running a stripped chunk,
then the error messages may not contain the full information they usually do.
For instance,
line numbers and names of local variables are lost.
.TP
.B \-v
show version information.
.SH FILES
.TP 15
.B luac.out
default output file
.SH "SEE ALSO"
.BR lua (1)
.br
http://www.lua.org/
.SH DIAGNOSTICS
Error messages should be self explanatory.
.SH AUTHORS
L. H. de Figueiredo,
R. Ierusalimschy and
W. Celes
.\" EOF
| xLua/build/lua-5.1.5/doc/luac.1/0 | {
"file_path": "xLua/build/lua-5.1.5/doc/luac.1",
"repo_id": "xLua",
"token_count": 1041
} | 2,079 |
/*
** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $
** Lua API
** See Copyright Notice in lua.h
*/
#include <assert.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#define lapi_c
#define LUA_CORE
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lundump.h"
#include "lvm.h"
const char lua_ident[] =
"$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n"
"$Authors: " LUA_AUTHORS " $\n"
"$URL: www.lua.org $\n";
#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))
#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject)
#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;}
static TValue *index2adr (lua_State *L, int idx) {
if (idx > 0) {
TValue *o = L->base + (idx - 1);
api_check(L, idx <= L->ci->top - L->base);
if (o >= L->top) return cast(TValue *, luaO_nilobject);
else return o;
}
else if (idx > LUA_REGISTRYINDEX) {
api_check(L, idx != 0 && -idx <= L->top - L->base);
return L->top + idx;
}
else switch (idx) { /* pseudo-indices */
case LUA_REGISTRYINDEX: return registry(L);
case LUA_ENVIRONINDEX: {
Closure *func = curr_func(L);
sethvalue(L, &L->env, func->c.env);
return &L->env;
}
case LUA_GLOBALSINDEX: return gt(L);
default: {
Closure *func = curr_func(L);
idx = LUA_GLOBALSINDEX - idx;
return (idx <= func->c.nupvalues)
? &func->c.upvalue[idx-1]
: cast(TValue *, luaO_nilobject);
}
}
}
static Table *getcurrenv (lua_State *L) {
if (L->ci == L->base_ci) /* no enclosing function? */
return hvalue(gt(L)); /* use global table as environment */
else {
Closure *func = curr_func(L);
return func->c.env;
}
}
void luaA_pushobject (lua_State *L, const TValue *o) {
setobj2s(L, L->top, o);
api_incr_top(L);
}
LUA_API int lua_checkstack (lua_State *L, int size) {
int res = 1;
lua_lock(L);
if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK)
res = 0; /* stack overflow */
else if (size > 0) {
luaD_checkstack(L, size);
if (L->ci->top < L->top + size)
L->ci->top = L->top + size;
}
lua_unlock(L);
return res;
}
LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
int i;
if (from == to) return;
lua_lock(to);
api_checknelems(from, n);
api_check(from, G(from) == G(to));
api_check(from, to->ci->top - to->top >= n);
from->top -= n;
for (i = 0; i < n; i++) {
setobj2s(to, to->top++, from->top + i);
}
lua_unlock(to);
}
LUA_API void lua_setlevel (lua_State *from, lua_State *to) {
to->nCcalls = from->nCcalls;
}
LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
lua_CFunction old;
lua_lock(L);
old = G(L)->panic;
G(L)->panic = panicf;
lua_unlock(L);
return old;
}
LUA_API lua_State *lua_newthread (lua_State *L) {
lua_State *L1;
lua_lock(L);
luaC_checkGC(L);
L1 = luaE_newthread(L);
setthvalue(L, L->top, L1);
api_incr_top(L);
lua_unlock(L);
luai_userstatethread(L, L1);
return L1;
}
/*
** basic stack manipulation
*/
LUA_API int lua_gettop (lua_State *L) {
return cast_int(L->top - L->base);
}
LUA_API void lua_settop (lua_State *L, int idx) {
lua_lock(L);
if (idx >= 0) {
api_check(L, idx <= L->stack_last - L->base);
while (L->top < L->base + idx)
setnilvalue(L->top++);
L->top = L->base + idx;
}
else {
api_check(L, -(idx+1) <= (L->top - L->base));
L->top += idx+1; /* `subtract' index (index is negative) */
}
lua_unlock(L);
}
LUA_API void lua_remove (lua_State *L, int idx) {
StkId p;
lua_lock(L);
p = index2adr(L, idx);
api_checkvalidindex(L, p);
while (++p < L->top) setobjs2s(L, p-1, p);
L->top--;
lua_unlock(L);
}
LUA_API void lua_insert (lua_State *L, int idx) {
StkId p;
StkId q;
lua_lock(L);
p = index2adr(L, idx);
api_checkvalidindex(L, p);
for (q = L->top; q>p; q--) setobjs2s(L, q, q-1);
setobjs2s(L, p, L->top);
lua_unlock(L);
}
LUA_API void lua_replace (lua_State *L, int idx) {
StkId o;
lua_lock(L);
/* explicit test for incompatible code */
if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci)
luaG_runerror(L, "no calling environment");
api_checknelems(L, 1);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
if (idx == LUA_ENVIRONINDEX) {
Closure *func = curr_func(L);
api_check(L, ttistable(L->top - 1));
func->c.env = hvalue(L->top - 1);
luaC_barrier(L, func, L->top - 1);
}
else {
setobj(L, o, L->top - 1);
if (idx < LUA_GLOBALSINDEX) /* function upvalue? */
luaC_barrier(L, curr_func(L), L->top - 1);
}
L->top--;
lua_unlock(L);
}
LUA_API void lua_pushvalue (lua_State *L, int idx) {
lua_lock(L);
setobj2s(L, L->top, index2adr(L, idx));
api_incr_top(L);
lua_unlock(L);
}
/*
** access functions (stack -> C)
*/
LUA_API int lua_type (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
}
LUA_API const char *lua_typename (lua_State *L, int t) {
UNUSED(L);
return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
}
LUA_API int lua_iscfunction (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return iscfunction(o);
}
LUA_API int lua_isnumber (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
return tonumber(o, &n);
}
LUA_API int lua_isstring (lua_State *L, int idx) {
int t = lua_type(L, idx);
return (t == LUA_TSTRING || t == LUA_TNUMBER);
}
LUA_API int lua_isuserdata (lua_State *L, int idx) {
const TValue *o = index2adr(L, idx);
return (ttisuserdata(o) || ttislightuserdata(o));
}
LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
StkId o1 = index2adr(L, index1);
StkId o2 = index2adr(L, index2);
return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
: luaO_rawequalObj(o1, o2);
}
LUA_API int lua_equal (lua_State *L, int index1, int index2) {
StkId o1, o2;
int i;
lua_lock(L); /* may call tag method */
o1 = index2adr(L, index1);
o2 = index2adr(L, index2);
i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2);
lua_unlock(L);
return i;
}
LUA_API int lua_lessthan (lua_State *L, int index1, int index2) {
StkId o1, o2;
int i;
lua_lock(L); /* may call tag method */
o1 = index2adr(L, index1);
o2 = index2adr(L, index2);
i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
: luaV_lessthan(L, o1, o2);
lua_unlock(L);
return i;
}
LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
if (tonumber(o, &n))
return nvalue(o);
else
return 0;
}
LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
if (tonumber(o, &n)) {
lua_Integer res;
lua_Number num = nvalue(o);
lua_number2integer(res, num);
return res;
}
else
return 0;
}
LUA_API int lua_toboolean (lua_State *L, int idx) {
const TValue *o = index2adr(L, idx);
return !l_isfalse(o);
}
LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
StkId o = index2adr(L, idx);
if (!ttisstring(o)) {
lua_lock(L); /* `luaV_tostring' may create a new string */
if (!luaV_tostring(L, o)) { /* conversion failed? */
if (len != NULL) *len = 0;
lua_unlock(L);
return NULL;
}
luaC_checkGC(L);
o = index2adr(L, idx); /* previous call may reallocate the stack */
lua_unlock(L);
}
if (len != NULL) *len = tsvalue(o)->len;
return svalue(o);
}
LUA_API size_t lua_objlen (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TSTRING: return tsvalue(o)->len;
case LUA_TUSERDATA: return uvalue(o)->len;
case LUA_TTABLE: return luaH_getn(hvalue(o));
case LUA_TNUMBER: {
size_t l;
lua_lock(L); /* `luaV_tostring' may create a new string */
l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0);
lua_unlock(L);
return l;
}
default: return 0;
}
}
LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (!iscfunction(o)) ? NULL : clvalue(o)->c.f;
}
LUA_API void *lua_touserdata (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TUSERDATA: return (rawuvalue(o) + 1);
case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL;
}
}
LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (!ttisthread(o)) ? NULL : thvalue(o);
}
LUA_API const void *lua_topointer (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TTABLE: return hvalue(o);
case LUA_TFUNCTION: return clvalue(o);
case LUA_TTHREAD: return thvalue(o);
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
return lua_touserdata(L, idx);
default: return NULL;
}
}
/*
** push functions (C -> stack)
*/
LUA_API void lua_pushnil (lua_State *L) {
lua_lock(L);
setnilvalue(L->top);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
lua_lock(L);
setnvalue(L->top, n);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
lua_lock(L);
setnvalue(L->top, cast_num(n));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) {
lua_lock(L);
luaC_checkGC(L);
setsvalue2s(L, L->top, luaS_newlstr(L, s, len));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushstring (lua_State *L, const char *s) {
if (s == NULL)
lua_pushnil(L);
else
lua_pushlstring(L, s, strlen(s));
}
LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
va_list argp) {
const char *ret;
lua_lock(L);
luaC_checkGC(L);
ret = luaO_pushvfstring(L, fmt, argp);
lua_unlock(L);
return ret;
}
LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
const char *ret;
va_list argp;
lua_lock(L);
luaC_checkGC(L);
va_start(argp, fmt);
ret = luaO_pushvfstring(L, fmt, argp);
va_end(argp);
lua_unlock(L);
return ret;
}
LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
Closure *cl;
lua_lock(L);
luaC_checkGC(L);
api_checknelems(L, n);
cl = luaF_newCclosure(L, n, getcurrenv(L));
cl->c.f = fn;
L->top -= n;
while (n--)
setobj2n(L, &cl->c.upvalue[n], L->top+n);
setclvalue(L, L->top, cl);
lua_assert(iswhite(obj2gco(cl)));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushboolean (lua_State *L, int b) {
lua_lock(L);
setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
lua_lock(L);
setpvalue(L->top, p);
api_incr_top(L);
lua_unlock(L);
}
LUA_API int lua_pushthread (lua_State *L) {
lua_lock(L);
setthvalue(L, L->top, L);
api_incr_top(L);
lua_unlock(L);
return (G(L)->mainthread == L);
}
/*
** get functions (Lua -> stack)
*/
LUA_API void lua_gettable (lua_State *L, int idx) {
StkId t;
lua_lock(L);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
luaV_gettable(L, t, L->top - 1, L->top - 1);
lua_unlock(L);
}
LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
StkId t;
TValue key;
lua_lock(L);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
setsvalue(L, &key, luaS_new(L, k));
luaV_gettable(L, t, &key, L->top);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_rawget (lua_State *L, int idx) {
StkId t;
lua_lock(L);
t = index2adr(L, idx);
api_check(L, ttistable(t));
setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
lua_unlock(L);
}
LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
StkId o;
lua_lock(L);
o = index2adr(L, idx);
api_check(L, ttistable(o));
setobj2s(L, L->top, luaH_getnum(hvalue(o), n));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
lua_lock(L);
luaC_checkGC(L);
sethvalue(L, L->top, luaH_new(L, narray, nrec));
api_incr_top(L);
lua_unlock(L);
}
LUA_API int lua_getmetatable (lua_State *L, int objindex) {
const TValue *obj;
Table *mt = NULL;
int res;
lua_lock(L);
obj = index2adr(L, objindex);
switch (ttype(obj)) {
case LUA_TTABLE:
mt = hvalue(obj)->metatable;
break;
case LUA_TUSERDATA:
mt = uvalue(obj)->metatable;
break;
default:
mt = G(L)->mt[ttype(obj)];
break;
}
if (mt == NULL)
res = 0;
else {
sethvalue(L, L->top, mt);
api_incr_top(L);
res = 1;
}
lua_unlock(L);
return res;
}
LUA_API void lua_getfenv (lua_State *L, int idx) {
StkId o;
lua_lock(L);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
switch (ttype(o)) {
case LUA_TFUNCTION:
sethvalue(L, L->top, clvalue(o)->c.env);
break;
case LUA_TUSERDATA:
sethvalue(L, L->top, uvalue(o)->env);
break;
case LUA_TTHREAD:
setobj2s(L, L->top, gt(thvalue(o)));
break;
default:
setnilvalue(L->top);
break;
}
api_incr_top(L);
lua_unlock(L);
}
/*
** set functions (stack -> Lua)
*/
LUA_API void lua_settable (lua_State *L, int idx) {
StkId t;
lua_lock(L);
api_checknelems(L, 2);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
luaV_settable(L, t, L->top - 2, L->top - 1);
L->top -= 2; /* pop index and value */
lua_unlock(L);
}
LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
StkId t;
TValue key;
lua_lock(L);
api_checknelems(L, 1);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
setsvalue(L, &key, luaS_new(L, k));
luaV_settable(L, t, &key, L->top - 1);
L->top--; /* pop value */
lua_unlock(L);
}
LUA_API void lua_rawset (lua_State *L, int idx) {
StkId t;
lua_lock(L);
api_checknelems(L, 2);
t = index2adr(L, idx);
api_check(L, ttistable(t));
setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
luaC_barriert(L, hvalue(t), L->top-1);
L->top -= 2;
lua_unlock(L);
}
LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
StkId o;
lua_lock(L);
api_checknelems(L, 1);
o = index2adr(L, idx);
api_check(L, ttistable(o));
setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1);
luaC_barriert(L, hvalue(o), L->top-1);
L->top--;
lua_unlock(L);
}
LUA_API int lua_setmetatable (lua_State *L, int objindex) {
TValue *obj;
Table *mt;
lua_lock(L);
api_checknelems(L, 1);
obj = index2adr(L, objindex);
api_checkvalidindex(L, obj);
if (ttisnil(L->top - 1))
mt = NULL;
else {
api_check(L, ttistable(L->top - 1));
mt = hvalue(L->top - 1);
}
switch (ttype(obj)) {
case LUA_TTABLE: {
hvalue(obj)->metatable = mt;
if (mt)
luaC_objbarriert(L, hvalue(obj), mt);
break;
}
case LUA_TUSERDATA: {
uvalue(obj)->metatable = mt;
if (mt)
luaC_objbarrier(L, rawuvalue(obj), mt);
break;
}
default: {
G(L)->mt[ttype(obj)] = mt;
break;
}
}
L->top--;
lua_unlock(L);
return 1;
}
LUA_API int lua_setfenv (lua_State *L, int idx) {
StkId o;
int res = 1;
lua_lock(L);
api_checknelems(L, 1);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
api_check(L, ttistable(L->top - 1));
switch (ttype(o)) {
case LUA_TFUNCTION:
clvalue(o)->c.env = hvalue(L->top - 1);
break;
case LUA_TUSERDATA:
uvalue(o)->env = hvalue(L->top - 1);
break;
case LUA_TTHREAD:
sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
break;
default:
res = 0;
break;
}
if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
L->top--;
lua_unlock(L);
return res;
}
/*
** `load' and `call' functions (run Lua code)
*/
#define adjustresults(L,nres) \
{ if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; }
#define checkresults(L,na,nr) \
api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)))
LUA_API void lua_call (lua_State *L, int nargs, int nresults) {
StkId func;
lua_lock(L);
api_checknelems(L, nargs+1);
checkresults(L, nargs, nresults);
func = L->top - (nargs+1);
luaD_call(L, func, nresults);
adjustresults(L, nresults);
lua_unlock(L);
}
/*
** Execute a protected call.
*/
struct CallS { /* data to `f_call' */
StkId func;
int nresults;
};
static void f_call (lua_State *L, void *ud) {
struct CallS *c = cast(struct CallS *, ud);
luaD_call(L, c->func, c->nresults);
}
LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) {
struct CallS c;
int status;
ptrdiff_t func;
lua_lock(L);
api_checknelems(L, nargs+1);
checkresults(L, nargs, nresults);
if (errfunc == 0)
func = 0;
else {
StkId o = index2adr(L, errfunc);
api_checkvalidindex(L, o);
func = savestack(L, o);
}
c.func = L->top - (nargs+1); /* function to be called */
c.nresults = nresults;
status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
adjustresults(L, nresults);
lua_unlock(L);
return status;
}
/*
** Execute a protected C call.
*/
struct CCallS { /* data to `f_Ccall' */
lua_CFunction func;
void *ud;
};
static void f_Ccall (lua_State *L, void *ud) {
struct CCallS *c = cast(struct CCallS *, ud);
Closure *cl;
cl = luaF_newCclosure(L, 0, getcurrenv(L));
cl->c.f = c->func;
setclvalue(L, L->top, cl); /* push function */
api_incr_top(L);
setpvalue(L->top, c->ud); /* push only argument */
api_incr_top(L);
luaD_call(L, L->top - 2, 0);
}
LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
struct CCallS c;
int status;
lua_lock(L);
c.func = func;
c.ud = ud;
status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0);
lua_unlock(L);
return status;
}
LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
const char *chunkname) {
ZIO z;
int status;
lua_lock(L);
if (!chunkname) chunkname = "?";
luaZ_init(L, &z, reader, data);
status = luaD_protectedparser(L, &z, chunkname);
lua_unlock(L);
return status;
}
LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
int status;
TValue *o;
lua_lock(L);
api_checknelems(L, 1);
o = L->top - 1;
if (isLfunction(o))
status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0);
else
status = 1;
lua_unlock(L);
return status;
}
LUA_API int lua_status (lua_State *L) {
return L->status;
}
/*
** Garbage-collection function
*/
LUA_API int lua_gc (lua_State *L, int what, int data) {
int res = 0;
global_State *g;
lua_lock(L);
g = G(L);
switch (what) {
case LUA_GCSTOP: {
g->GCthreshold = MAX_LUMEM;
break;
}
case LUA_GCRESTART: {
g->GCthreshold = g->totalbytes;
break;
}
case LUA_GCCOLLECT: {
luaC_fullgc(L);
break;
}
case LUA_GCCOUNT: {
/* GC values are expressed in Kbytes: #bytes/2^10 */
res = cast_int(g->totalbytes >> 10);
break;
}
case LUA_GCCOUNTB: {
res = cast_int(g->totalbytes & 0x3ff);
break;
}
case LUA_GCSTEP: {
lu_mem a = (cast(lu_mem, data) << 10);
if (a <= g->totalbytes)
g->GCthreshold = g->totalbytes - a;
else
g->GCthreshold = 0;
while (g->GCthreshold <= g->totalbytes) {
luaC_step(L);
if (g->gcstate == GCSpause) { /* end of cycle? */
res = 1; /* signal it */
break;
}
}
break;
}
case LUA_GCSETPAUSE: {
res = g->gcpause;
g->gcpause = data;
break;
}
case LUA_GCSETSTEPMUL: {
res = g->gcstepmul;
g->gcstepmul = data;
break;
}
default: res = -1; /* invalid option */
}
lua_unlock(L);
return res;
}
/*
** miscellaneous functions
*/
LUA_API int lua_error (lua_State *L) {
lua_lock(L);
api_checknelems(L, 1);
luaG_errormsg(L);
lua_unlock(L);
return 0; /* to avoid warnings */
}
LUA_API int lua_next (lua_State *L, int idx) {
StkId t;
int more;
lua_lock(L);
t = index2adr(L, idx);
api_check(L, ttistable(t));
more = luaH_next(L, hvalue(t), L->top - 1);
if (more) {
api_incr_top(L);
}
else /* no more elements */
L->top -= 1; /* remove key */
lua_unlock(L);
return more;
}
LUA_API void lua_concat (lua_State *L, int n) {
lua_lock(L);
api_checknelems(L, n);
if (n >= 2) {
luaC_checkGC(L);
luaV_concat(L, n, cast_int(L->top - L->base) - 1);
L->top -= (n-1);
}
else if (n == 0) { /* push empty string */
setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
api_incr_top(L);
}
/* else n == 1; nothing to do */
lua_unlock(L);
}
LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
lua_Alloc f;
lua_lock(L);
if (ud) *ud = G(L)->ud;
f = G(L)->frealloc;
lua_unlock(L);
return f;
}
LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
lua_lock(L);
G(L)->ud = ud;
G(L)->frealloc = f;
lua_unlock(L);
}
LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
Udata *u;
lua_lock(L);
luaC_checkGC(L);
u = luaS_newudata(L, size, getcurrenv(L));
setuvalue(L, L->top, u);
api_incr_top(L);
lua_unlock(L);
return u + 1;
}
static const char *aux_upvalue (StkId fi, int n, TValue **val) {
Closure *f;
if (!ttisfunction(fi)) return NULL;
f = clvalue(fi);
if (f->c.isC) {
if (!(1 <= n && n <= f->c.nupvalues)) return NULL;
*val = &f->c.upvalue[n-1];
return "";
}
else {
Proto *p = f->l.p;
if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
*val = f->l.upvals[n-1]->v;
return getstr(p->upvalues[n-1]);
}
}
LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val;
lua_lock(L);
name = aux_upvalue(index2adr(L, funcindex), n, &val);
if (name) {
setobj2s(L, L->top, val);
api_incr_top(L);
}
lua_unlock(L);
return name;
}
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val;
StkId fi;
lua_lock(L);
fi = index2adr(L, funcindex);
api_checknelems(L, 1);
name = aux_upvalue(fi, n, &val);
if (name) {
L->top--;
setobj(L, val, L->top);
luaC_barrier(L, clvalue(fi), L->top);
}
lua_unlock(L);
return name;
}
| xLua/build/lua-5.1.5/src/lapi.c/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lapi.c",
"repo_id": "xLua",
"token_count": 11127
} | 2,080 |
/*
** $Id: lgc.h,v 2.15.1.1 2007/12/27 13:02:25 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
#ifndef lgc_h
#define lgc_h
#include "lobject.h"
/*
** Possible states of the Garbage Collector
*/
#define GCSpause 0
#define GCSpropagate 1
#define GCSsweepstring 2
#define GCSsweep 3
#define GCSfinalize 4
/*
** some userful bit tricks
*/
#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m)))
#define setbits(x,m) ((x) |= (m))
#define testbits(x,m) ((x) & (m))
#define bitmask(b) (1<<(b))
#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
#define l_setbit(x,b) setbits(x, bitmask(b))
#define resetbit(x,b) resetbits(x, bitmask(b))
#define testbit(x,b) testbits(x, bitmask(b))
#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2)))
#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2)))
#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2)))
/*
** Layout for bit use in `marked' field:
** bit 0 - object is white (type 0)
** bit 1 - object is white (type 1)
** bit 2 - object is black
** bit 3 - for userdata: has been finalized
** bit 3 - for tables: has weak keys
** bit 4 - for tables: has weak values
** bit 5 - object is fixed (should not be collected)
** bit 6 - object is "super" fixed (only the main thread)
*/
#define WHITE0BIT 0
#define WHITE1BIT 1
#define BLACKBIT 2
#define FINALIZEDBIT 3
#define KEYWEAKBIT 3
#define VALUEWEAKBIT 4
#define FIXEDBIT 5
#define SFIXEDBIT 6
#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
#define isblack(x) testbit((x)->gch.marked, BLACKBIT)
#define isgray(x) (!isblack(x) && !iswhite(x))
#define otherwhite(g) (g->currentwhite ^ WHITEBITS)
#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS)
#define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
#define luaC_checkGC(L) { \
condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \
if (G(L)->totalbytes >= G(L)->GCthreshold) \
luaC_step(L); }
#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),gcvalue(v)); }
#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \
luaC_barrierback(L,t); }
#define luaC_objbarrier(L,p,o) \
{ if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),obj2gco(o)); }
#define luaC_objbarriert(L,t,o) \
{ if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); }
LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all);
LUAI_FUNC void luaC_callGCTM (lua_State *L);
LUAI_FUNC void luaC_freeall (lua_State *L);
LUAI_FUNC void luaC_step (lua_State *L);
LUAI_FUNC void luaC_fullgc (lua_State *L);
LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
#endif
| xLua/build/lua-5.1.5/src/lgc.h/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lgc.h",
"repo_id": "xLua",
"token_count": 1421
} | 2,081 |
/*
** $Id: lparser.h,v 1.57.1.1 2007/12/27 13:02:25 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
*/
#ifndef lparser_h
#define lparser_h
#include "llimits.h"
#include "lobject.h"
#include "lzio.h"
/*
** Expression descriptor
*/
typedef enum {
VVOID, /* no value */
VNIL,
VTRUE,
VFALSE,
VK, /* info = index of constant in `k' */
VKNUM, /* nval = numerical value */
VLOCAL, /* info = local register */
VUPVAL, /* info = index of upvalue in `upvalues' */
VGLOBAL, /* info = index of table; aux = index of global name in `k' */
VINDEXED, /* info = table register; aux = index register (or `k') */
VJMP, /* info = instruction pc */
VRELOCABLE, /* info = instruction pc */
VNONRELOC, /* info = result register */
VCALL, /* info = instruction pc */
VVARARG /* info = instruction pc */
} expkind;
typedef struct expdesc {
expkind k;
union {
struct { int info, aux; } s;
lua_Number nval;
} u;
int t; /* patch list of `exit when true' */
int f; /* patch list of `exit when false' */
} expdesc;
typedef struct upvaldesc {
lu_byte k;
lu_byte info;
} upvaldesc;
struct BlockCnt; /* defined in lparser.c */
/* state needed to generate code for a given function */
typedef struct FuncState {
Proto *f; /* current function header */
Table *h; /* table to find (and reuse) elements in `k' */
struct FuncState *prev; /* enclosing function */
struct LexState *ls; /* lexical state */
struct lua_State *L; /* copy of the Lua state */
struct BlockCnt *bl; /* chain of current blocks */
int pc; /* next position to code (equivalent to `ncode') */
int lasttarget; /* `pc' of last `jump target' */
int jpc; /* list of pending jumps to `pc' */
int freereg; /* first free register */
int nk; /* number of elements in `k' */
int np; /* number of elements in `p' */
short nlocvars; /* number of elements in `locvars' */
lu_byte nactvar; /* number of active local variables */
upvaldesc upvalues[LUAI_MAXUPVALUES]; /* upvalues */
unsigned short actvar[LUAI_MAXVARS]; /* declared-variable stack */
} FuncState;
LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
const char *name);
#endif
| xLua/build/lua-5.1.5/src/lparser.h/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lparser.h",
"repo_id": "xLua",
"token_count": 860
} | 2,082 |
/*
** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $
** load precompiled Lua chunks
** See Copyright Notice in lua.h
*/
#include <string.h>
#define lundump_c
#define LUA_CORE
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstring.h"
#include "lundump.h"
#include "lzio.h"
typedef struct {
lua_State* L;
ZIO* Z;
Mbuffer* b;
const char* name;
} LoadState;
#ifdef LUAC_TRUST_BINARIES
#define IF(c,s)
#define error(S,s)
#else
#define IF(c,s) if (c) error(S,s)
static void error(LoadState* S, const char* why)
{
luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why);
luaD_throw(S->L,LUA_ERRSYNTAX);
}
#endif
#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size))
#define LoadByte(S) (lu_byte)LoadChar(S)
#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
static void LoadBlock(LoadState* S, void* b, size_t size)
{
size_t r=luaZ_read(S->Z,b,size);
IF (r!=0, "unexpected end");
}
static int LoadChar(LoadState* S)
{
char x;
LoadVar(S,x);
return x;
}
static int LoadInt(LoadState* S)
{
int x;
LoadVar(S,x);
IF (x<0, "bad integer");
return x;
}
static lua_Number LoadNumber(LoadState* S)
{
lua_Number x;
LoadVar(S,x);
return x;
}
static TString* LoadString(LoadState* S)
{
size_t size;
LoadVar(S,size);
if (size==0)
return NULL;
else
{
char* s=luaZ_openspace(S->L,S->b,size);
LoadBlock(S,s,size);
return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
}
}
static void LoadCode(LoadState* S, Proto* f)
{
int n=LoadInt(S);
f->code=luaM_newvector(S->L,n,Instruction);
f->sizecode=n;
LoadVector(S,f->code,n,sizeof(Instruction));
}
static Proto* LoadFunction(LoadState* S, TString* p);
static void LoadConstants(LoadState* S, Proto* f)
{
int i,n;
n=LoadInt(S);
f->k=luaM_newvector(S->L,n,TValue);
f->sizek=n;
for (i=0; i<n; i++) setnilvalue(&f->k[i]);
for (i=0; i<n; i++)
{
TValue* o=&f->k[i];
int t=LoadChar(S);
switch (t)
{
case LUA_TNIL:
setnilvalue(o);
break;
case LUA_TBOOLEAN:
setbvalue(o,LoadChar(S)!=0);
break;
case LUA_TNUMBER:
setnvalue(o,LoadNumber(S));
break;
case LUA_TSTRING:
setsvalue2n(S->L,o,LoadString(S));
break;
default:
error(S,"bad constant");
break;
}
}
n=LoadInt(S);
f->p=luaM_newvector(S->L,n,Proto*);
f->sizep=n;
for (i=0; i<n; i++) f->p[i]=NULL;
for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
}
static void LoadDebug(LoadState* S, Proto* f)
{
int i,n;
n=LoadInt(S);
f->lineinfo=luaM_newvector(S->L,n,int);
f->sizelineinfo=n;
LoadVector(S,f->lineinfo,n,sizeof(int));
n=LoadInt(S);
f->locvars=luaM_newvector(S->L,n,LocVar);
f->sizelocvars=n;
for (i=0; i<n; i++) f->locvars[i].varname=NULL;
for (i=0; i<n; i++)
{
f->locvars[i].varname=LoadString(S);
f->locvars[i].startpc=LoadInt(S);
f->locvars[i].endpc=LoadInt(S);
}
n=LoadInt(S);
f->upvalues=luaM_newvector(S->L,n,TString*);
f->sizeupvalues=n;
for (i=0; i<n; i++) f->upvalues[i]=NULL;
for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
}
static Proto* LoadFunction(LoadState* S, TString* p)
{
Proto* f;
if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
f=luaF_newproto(S->L);
setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
f->source=LoadString(S); if (f->source==NULL) f->source=p;
f->linedefined=LoadInt(S);
f->lastlinedefined=LoadInt(S);
f->nups=LoadByte(S);
f->numparams=LoadByte(S);
f->is_vararg=LoadByte(S);
f->maxstacksize=LoadByte(S);
LoadCode(S,f);
LoadConstants(S,f);
LoadDebug(S,f);
IF (!luaG_checkcode(f), "bad code");
S->L->top--;
S->L->nCcalls--;
return f;
}
static void LoadHeader(LoadState* S)
{
char h[LUAC_HEADERSIZE];
char s[LUAC_HEADERSIZE];
luaU_header(h);
LoadBlock(S,s,LUAC_HEADERSIZE);
IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header");
}
/*
** load precompiled chunk
*/
Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
{
LoadState S;
if (*name=='@' || *name=='=')
S.name=name+1;
else if (*name==LUA_SIGNATURE[0])
S.name="binary string";
else
S.name=name;
S.L=L;
S.Z=Z;
S.b=buff;
LoadHeader(&S);
return LoadFunction(&S,luaS_newliteral(L,"=?"));
}
/*
* make header
*/
void luaU_header (char* h)
{
int x=1;
memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
h+=sizeof(LUA_SIGNATURE)-1;
*h++=(char)LUAC_VERSION;
*h++=(char)LUAC_FORMAT;
*h++=(char)*(char*)&x; /* endianness */
*h++=(char)sizeof(int);
*h++=(char)sizeof(size_t);
*h++=(char)sizeof(Instruction);
*h++=(char)sizeof(lua_Number);
*h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */
}
| xLua/build/lua-5.1.5/src/lundump.c/0 | {
"file_path": "xLua/build/lua-5.1.5/src/lundump.c",
"repo_id": "xLua",
"token_count": 2192
} | 2,083 |
ul {
list-style-type: none ;
}
ul.contents {
padding: 0 ;
}
table {
border: none ;
border-spacing: 0 ;
border-collapse: collapse ;
}
td {
vertical-align: top ;
padding: 0 ;
text-align: left ;
line-height: 1.25 ;
width: 15% ;
}
| xLua/build/lua-5.3.3/doc/index.css/0 | {
"file_path": "xLua/build/lua-5.3.3/doc/index.css",
"repo_id": "xLua",
"token_count": 106
} | 2,084 |
/*
** $Id: lauxlib.h,v 1.129 2015/11/23 11:29:43 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#ifndef lauxlib_h
#define lauxlib_h
#include <stddef.h>
#include <stdio.h>
#include "lua.h"
/* extra error code for 'luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1)
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number))
LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);
#define luaL_checkversion(L) \
luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)
LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
size_t *l);
LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
const char *def, size_t *l);
LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
lua_Integer def);
LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);
LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void (luaL_where) (lua_State *L, int lvl);
LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
const char *const lst[]);
LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
/* predefined references */
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
LUALIB_API int (luaL_ref) (lua_State *L, int t);
LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename,
const char *mode);
#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)
LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
const char *name, const char *mode);
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void);
LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
const char *r);
LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
const char *msg, int level);
LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
lua_CFunction openf, int glb);
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#define luaL_newlibtable(L,l) \
lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
#define luaL_newlib(L,l) \
(luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
#define luaL_argcheck(L, cond,arg,extramsg) \
((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
#define luaL_dofile(L, fn) \
(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_dostring(L, s) \
(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
typedef struct luaL_Buffer {
char *b; /* buffer address */
size_t size; /* buffer size */
size_t n; /* number of characters in buffer */
lua_State *L;
char initb[LUAL_BUFFERSIZE]; /* initial buffer */
} luaL_Buffer;
#define luaL_addchar(B,c) \
((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \
((B)->b[(B)->n++] = (c)))
#define luaL_addsize(B,s) ((B)->n += (s))
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);
LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
/* }====================================================== */
/*
** {======================================================
** File handles for IO library
** =======================================================
*/
/*
** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and
** initial structure 'luaL_Stream' (it may contain other fields
** after that initial structure).
*/
#define LUA_FILEHANDLE "FILE*"
typedef struct luaL_Stream {
FILE *f; /* stream (NULL for incompletely created streams) */
lua_CFunction closef; /* to close stream (NULL for closed streams) */
} luaL_Stream;
/* }====================================================== */
/* compatibility with old module system */
#if defined(LUA_COMPAT_MODULE)
LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,
int sizehint);
LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
const luaL_Reg *l, int nup);
#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))
#endif
/*
** {==================================================================
** "Abstraction Layer" for basic report of messages and errors
** ===================================================================
*/
/* print a string */
#if !defined(lua_writestring)
#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
#endif
/* print a newline and flush the output */
#if !defined(lua_writeline)
#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout))
#endif
/* print an error message */
#if !defined(lua_writestringerror)
#define lua_writestringerror(s,p) \
(fprintf(stderr, (s), (p)), fflush(stderr))
#endif
/* }================================================================== */
/*
** {============================================================
** Compatibility with deprecated conversions
** =============================================================
*/
#if defined(LUA_COMPAT_APIINTCASTS)
#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a))
#define luaL_optunsigned(L,a,d) \
((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#endif
/* }============================================================ */
#endif
| xLua/build/lua-5.3.3/src/lauxlib.h/0 | {
"file_path": "xLua/build/lua-5.3.3/src/lauxlib.h",
"repo_id": "xLua",
"token_count": 3595
} | 2,085 |
/*
** $Id: lgc.c,v 2.212 2016/03/31 19:02:03 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
#define lgc_c
#define LUA_CORE
#include "lprefix.h"
#include <string.h>
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
/*
** internal state for collector while inside the atomic phase. The
** collector should never be in this state while running regular code.
*/
#define GCSinsideatomic (GCSpause + 1)
/*
** cost of sweeping one element (the size of a small object divided
** by some adjust for the sweep speed)
*/
#define GCSWEEPCOST ((sizeof(TString) + 4) / 4)
/* maximum number of elements to sweep in each single step */
#define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
/* cost of calling one finalizer */
#define GCFINALIZECOST GCSWEEPCOST
/*
** macro to adjust 'stepmul': 'stepmul' is actually used like
** 'stepmul / STEPMULADJ' (value chosen by tests)
*/
#define STEPMULADJ 200
/*
** macro to adjust 'pause': 'pause' is actually used like
** 'pause / PAUSEADJ' (value chosen by tests)
*/
#define PAUSEADJ 100
/*
** 'makewhite' erases all color bits then sets only the current white
** bit
*/
#define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
#define makewhite(g,x) \
(x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
#define white2gray(x) resetbits(x->marked, WHITEBITS)
#define black2gray(x) resetbit(x->marked, BLACKBIT)
#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
#define checkconsistency(obj) \
lua_longassert(!iscollectable(obj) || righttt(obj))
#define markvalue(g,o) { checkconsistency(o); \
if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
#define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); }
/*
** mark an object that can be NULL (either because it is really optional,
** or it was stripped as debug info, or inside an uncompleted structure)
*/
#define markobjectN(g,t) { if (t) markobject(g,t); }
static void reallymarkobject (global_State *g, GCObject *o);
/*
** {======================================================
** Generic functions
** =======================================================
*/
/*
** one after last element in a hash array
*/
#define gnodelast(h) gnode(h, cast(size_t, sizenode(h)))
/*
** link collectable object 'o' into list pointed by 'p'
*/
#define linkgclist(o,p) ((o)->gclist = (p), (p) = obj2gco(o))
/*
** If key is not marked, mark its entry as dead. This allows key to be
** collected, but keeps its entry in the table. A dead node is needed
** when Lua looks up for a key (it may be part of a chain) and when
** traversing a weak table (key might be removed from the table during
** traversal). Other places never manipulate dead keys, because its
** associated nil value is enough to signal that the entry is logically
** empty.
*/
static void removeentry (Node *n) {
lua_assert(ttisnil(gval(n)));
if (valiswhite(gkey(n)))
setdeadvalue(wgkey(n)); /* unused and unmarked key; remove it */
}
/*
** tells whether a key or value can be cleared from a weak
** table. Non-collectable objects are never removed from weak
** tables. Strings behave as 'values', so are never removed too. for
** other objects: if really collected, cannot keep them; for objects
** being finalized, keep them in keys, but not in values
*/
static int iscleared (global_State *g, const TValue *o) {
if (!iscollectable(o)) return 0;
else if (ttisstring(o)) {
markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */
return 0;
}
else return iswhite(gcvalue(o));
}
/*
** barrier that moves collector forward, that is, mark the white object
** being pointed by a black object. (If in sweep phase, clear the black
** object to white [sweep it] to avoid other barrier calls for this
** same object.)
*/
void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
global_State *g = G(L);
lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
if (keepinvariant(g)) /* must keep invariant? */
reallymarkobject(g, v); /* restore invariant */
else { /* sweep phase */
lua_assert(issweepphase(g));
makewhite(g, o); /* mark main obj. as white to avoid other barriers */
}
}
/*
** barrier that moves collector backward, that is, mark the black object
** pointing to a white object as gray again.
*/
void luaC_barrierback_ (lua_State *L, Table *t) {
global_State *g = G(L);
lua_assert(isblack(t) && !isdead(g, t));
black2gray(t); /* make table gray (again) */
linkgclist(t, g->grayagain);
}
/*
** barrier for assignments to closed upvalues. Because upvalues are
** shared among closures, it is impossible to know the color of all
** closures pointing to it. So, we assume that the object being assigned
** must be marked.
*/
void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
global_State *g = G(L);
GCObject *o = gcvalue(uv->v);
lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
if (keepinvariant(g))
markobject(g, o);
}
void luaC_fix (lua_State *L, GCObject *o) {
global_State *g = G(L);
lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
white2gray(o); /* they will be gray forever */
g->allgc = o->next; /* remove object from 'allgc' list */
o->next = g->fixedgc; /* link it to 'fixedgc' list */
g->fixedgc = o;
}
/*
** create a new collectable object (with given type and size) and link
** it to 'allgc' list.
*/
GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
global_State *g = G(L);
GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
o->marked = luaC_white(g);
o->tt = tt;
o->next = g->allgc;
g->allgc = o;
return o;
}
/* }====================================================== */
/*
** {======================================================
** Mark functions
** =======================================================
*/
/*
** mark an object. Userdata, strings, and closed upvalues are visited
** and turned black here. Other objects are marked gray and added
** to appropriate list to be visited (and turned black) later. (Open
** upvalues are already linked in 'headuv' list.)
*/
static void reallymarkobject (global_State *g, GCObject *o) {
reentry:
white2gray(o);
switch (o->tt) {
case LUA_TSHRSTR: {
gray2black(o);
g->GCmemtrav += sizelstring(gco2ts(o)->shrlen);
break;
}
case LUA_TLNGSTR: {
gray2black(o);
g->GCmemtrav += sizelstring(gco2ts(o)->u.lnglen);
break;
}
case LUA_TUSERDATA: {
TValue uvalue;
markobjectN(g, gco2u(o)->metatable); /* mark its metatable */
gray2black(o);
g->GCmemtrav += sizeudata(gco2u(o));
getuservalue(g->mainthread, gco2u(o), &uvalue);
if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
o = gcvalue(&uvalue);
goto reentry;
}
break;
}
case LUA_TLCL: {
linkgclist(gco2lcl(o), g->gray);
break;
}
case LUA_TCCL: {
linkgclist(gco2ccl(o), g->gray);
break;
}
case LUA_TTABLE: {
linkgclist(gco2t(o), g->gray);
break;
}
case LUA_TTHREAD: {
linkgclist(gco2th(o), g->gray);
break;
}
case LUA_TPROTO: {
linkgclist(gco2p(o), g->gray);
break;
}
default: lua_assert(0); break;
}
}
/*
** mark metamethods for basic types
*/
static void markmt (global_State *g) {
int i;
for (i=0; i < LUA_NUMTAGS; i++)
markobjectN(g, g->mt[i]);
}
/*
** mark all objects in list of being-finalized
*/
static void markbeingfnz (global_State *g) {
GCObject *o;
for (o = g->tobefnz; o != NULL; o = o->next)
markobject(g, o);
}
/*
** Mark all values stored in marked open upvalues from non-marked threads.
** (Values from marked threads were already marked when traversing the
** thread.) Remove from the list threads that no longer have upvalues and
** not-marked threads.
*/
static void remarkupvals (global_State *g) {
lua_State *thread;
lua_State **p = &g->twups;
while ((thread = *p) != NULL) {
lua_assert(!isblack(thread)); /* threads are never black */
if (isgray(thread) && thread->openupval != NULL)
p = &thread->twups; /* keep marked thread with upvalues in the list */
else { /* thread is not marked or without upvalues */
UpVal *uv;
*p = thread->twups; /* remove thread from the list */
thread->twups = thread; /* mark that it is out of list */
for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
if (uv->u.open.touched) {
markvalue(g, uv->v); /* remark upvalue's value */
uv->u.open.touched = 0;
}
}
}
}
}
/*
** mark root set and reset all gray lists, to start a new collection
*/
static void restartcollection (global_State *g) {
g->gray = g->grayagain = NULL;
g->weak = g->allweak = g->ephemeron = NULL;
markobject(g, g->mainthread);
markvalue(g, &g->l_registry);
markmt(g);
markbeingfnz(g); /* mark any finalizing object left from previous cycle */
}
/* }====================================================== */
/*
** {======================================================
** Traverse functions
** =======================================================
*/
/*
** Traverse a table with weak values and link it to proper list. During
** propagate phase, keep it in 'grayagain' list, to be revisited in the
** atomic phase. In the atomic phase, if table has any white value,
** put it in 'weak' list, to be cleared.
*/
static void traverseweakvalue (global_State *g, Table *h) {
Node *n, *limit = gnodelast(h);
/* if there is array part, assume it may have white values (it is not
worth traversing it now just to check) */
int hasclears = (h->sizearray > 0);
for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */
removeentry(n); /* remove it */
else {
lua_assert(!ttisnil(gkey(n)));
markvalue(g, gkey(n)); /* mark key */
if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */
hasclears = 1; /* table will have to be cleared */
}
}
if (g->gcstate == GCSpropagate)
linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
else if (hasclears)
linkgclist(h, g->weak); /* has to be cleared later */
}
/*
** Traverse an ephemeron table and link it to proper list. Returns true
** iff any object was marked during this traversal (which implies that
** convergence has to continue). During propagation phase, keep table
** in 'grayagain' list, to be visited again in the atomic phase. In
** the atomic phase, if table has any white->white entry, it has to
** be revisited during ephemeron convergence (as that key may turn
** black). Otherwise, if it has any white key, table has to be cleared
** (in the atomic phase).
*/
static int traverseephemeron (global_State *g, Table *h) {
int marked = 0; /* true if an object is marked in this traversal */
int hasclears = 0; /* true if table has white keys */
int hasww = 0; /* true if table has entry "white-key -> white-value" */
Node *n, *limit = gnodelast(h);
unsigned int i;
/* traverse array part */
for (i = 0; i < h->sizearray; i++) {
if (valiswhite(&h->array[i])) {
marked = 1;
reallymarkobject(g, gcvalue(&h->array[i]));
}
}
/* traverse hash part */
for (n = gnode(h, 0); n < limit; n++) {
checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */
removeentry(n); /* remove it */
else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */
hasclears = 1; /* table must be cleared */
if (valiswhite(gval(n))) /* value not marked yet? */
hasww = 1; /* white-white entry */
}
else if (valiswhite(gval(n))) { /* value not marked yet? */
marked = 1;
reallymarkobject(g, gcvalue(gval(n))); /* mark it now */
}
}
/* link table into proper list */
if (g->gcstate == GCSpropagate)
linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */
else if (hasww) /* table has white->white entries? */
linkgclist(h, g->ephemeron); /* have to propagate again */
else if (hasclears) /* table has white keys? */
linkgclist(h, g->allweak); /* may have to clean white keys */
return marked;
}
static void traversestrongtable (global_State *g, Table *h) {
Node *n, *limit = gnodelast(h);
unsigned int i;
for (i = 0; i < h->sizearray; i++) /* traverse array part */
markvalue(g, &h->array[i]);
for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
checkdeadkey(n);
if (ttisnil(gval(n))) /* entry is empty? */
removeentry(n); /* remove it */
else {
lua_assert(!ttisnil(gkey(n)));
markvalue(g, gkey(n)); /* mark key */
markvalue(g, gval(n)); /* mark value */
}
}
}
static lu_mem traversetable (global_State *g, Table *h) {
const char *weakkey, *weakvalue;
const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
markobjectN(g, h->metatable);
if (mode && ttisstring(mode) && /* is there a weak mode? */
((weakkey = strchr(svalue(mode), 'k')),
(weakvalue = strchr(svalue(mode), 'v')),
(weakkey || weakvalue))) { /* is really weak? */
black2gray(h); /* keep table gray */
if (!weakkey) /* strong keys? */
traverseweakvalue(g, h);
else if (!weakvalue) /* strong values? */
traverseephemeron(g, h);
else /* all weak */
linkgclist(h, g->allweak); /* nothing to traverse now */
}
else /* not weak */
traversestrongtable(g, h);
return sizeof(Table) + sizeof(TValue) * h->sizearray +
sizeof(Node) * cast(size_t, sizenode(h));
}
/*
** Traverse a prototype. (While a prototype is being build, its
** arrays can be larger than needed; the extra slots are filled with
** NULL, so the use of 'markobjectN')
*/
static int traverseproto (global_State *g, Proto *f) {
int i;
if (f->cache && iswhite(f->cache))
f->cache = NULL; /* allow cache to be collected */
markobjectN(g, f->source);
for (i = 0; i < f->sizek; i++) /* mark literals */
markvalue(g, &f->k[i]);
for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
markobjectN(g, f->upvalues[i].name);
for (i = 0; i < f->sizep; i++) /* mark nested protos */
markobjectN(g, f->p[i]);
for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
markobjectN(g, f->locvars[i].varname);
return sizeof(Proto) + sizeof(Instruction) * f->sizecode +
sizeof(Proto *) * f->sizep +
sizeof(TValue) * f->sizek +
sizeof(int) * f->sizelineinfo +
sizeof(LocVar) * f->sizelocvars +
sizeof(Upvaldesc) * f->sizeupvalues;
}
static lu_mem traverseCclosure (global_State *g, CClosure *cl) {
int i;
for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
markvalue(g, &cl->upvalue[i]);
return sizeCclosure(cl->nupvalues);
}
/*
** open upvalues point to values in a thread, so those values should
** be marked when the thread is traversed except in the atomic phase
** (because then the value cannot be changed by the thread and the
** thread may not be traversed again)
*/
static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
int i;
markobjectN(g, cl->p); /* mark its prototype */
for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
UpVal *uv = cl->upvals[i];
if (uv != NULL) {
if (upisopen(uv) && g->gcstate != GCSinsideatomic)
uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
else
markvalue(g, uv->v);
}
}
return sizeLclosure(cl->nupvalues);
}
static lu_mem traversethread (global_State *g, lua_State *th) {
StkId o = th->stack;
if (o == NULL)
return 1; /* stack not completely built yet */
lua_assert(g->gcstate == GCSinsideatomic ||
th->openupval == NULL || isintwups(th));
for (; o < th->top; o++) /* mark live elements in the stack */
markvalue(g, o);
if (g->gcstate == GCSinsideatomic) { /* final traversal? */
StkId lim = th->stack + th->stacksize; /* real end of stack */
for (; o < lim; o++) /* clear not-marked stack slice */
setnilvalue(o);
/* 'remarkupvals' may have removed thread from 'twups' list */
if (!isintwups(th) && th->openupval != NULL) {
th->twups = g->twups; /* link it back to the list */
g->twups = th;
}
}
else if (g->gckind != KGC_EMERGENCY)
luaD_shrinkstack(th); /* do not change stack in emergency cycle */
return (sizeof(lua_State) + sizeof(TValue) * th->stacksize +
sizeof(CallInfo) * th->nci);
}
/*
** traverse one gray object, turning it to black (except for threads,
** which are always gray).
*/
static void propagatemark (global_State *g) {
lu_mem size;
GCObject *o = g->gray;
lua_assert(isgray(o));
gray2black(o);
switch (o->tt) {
case LUA_TTABLE: {
Table *h = gco2t(o);
g->gray = h->gclist; /* remove from 'gray' list */
size = traversetable(g, h);
break;
}
case LUA_TLCL: {
LClosure *cl = gco2lcl(o);
g->gray = cl->gclist; /* remove from 'gray' list */
size = traverseLclosure(g, cl);
break;
}
case LUA_TCCL: {
CClosure *cl = gco2ccl(o);
g->gray = cl->gclist; /* remove from 'gray' list */
size = traverseCclosure(g, cl);
break;
}
case LUA_TTHREAD: {
lua_State *th = gco2th(o);
g->gray = th->gclist; /* remove from 'gray' list */
linkgclist(th, g->grayagain); /* insert into 'grayagain' list */
black2gray(o);
size = traversethread(g, th);
break;
}
case LUA_TPROTO: {
Proto *p = gco2p(o);
g->gray = p->gclist; /* remove from 'gray' list */
size = traverseproto(g, p);
break;
}
default: lua_assert(0); return;
}
g->GCmemtrav += size;
}
static void propagateall (global_State *g) {
while (g->gray) propagatemark(g);
}
static void convergeephemerons (global_State *g) {
int changed;
do {
GCObject *w;
GCObject *next = g->ephemeron; /* get ephemeron list */
g->ephemeron = NULL; /* tables may return to this list when traversed */
changed = 0;
while ((w = next) != NULL) {
next = gco2t(w)->gclist;
if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
propagateall(g); /* propagate changes */
changed = 1; /* will have to revisit all ephemeron tables */
}
}
} while (changed);
}
/* }====================================================== */
/*
** {======================================================
** Sweep Functions
** =======================================================
*/
/*
** clear entries with unmarked keys from all weaktables in list 'l' up
** to element 'f'
*/
static void clearkeys (global_State *g, GCObject *l, GCObject *f) {
for (; l != f; l = gco2t(l)->gclist) {
Table *h = gco2t(l);
Node *n, *limit = gnodelast(h);
for (n = gnode(h, 0); n < limit; n++) {
if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) {
setnilvalue(gval(n)); /* remove value ... */
removeentry(n); /* and remove entry from table */
}
}
}
}
/*
** clear entries with unmarked values from all weaktables in list 'l' up
** to element 'f'
*/
static void clearvalues (global_State *g, GCObject *l, GCObject *f) {
for (; l != f; l = gco2t(l)->gclist) {
Table *h = gco2t(l);
Node *n, *limit = gnodelast(h);
unsigned int i;
for (i = 0; i < h->sizearray; i++) {
TValue *o = &h->array[i];
if (iscleared(g, o)) /* value was collected? */
setnilvalue(o); /* remove value */
}
for (n = gnode(h, 0); n < limit; n++) {
if (!ttisnil(gval(n)) && iscleared(g, gval(n))) {
setnilvalue(gval(n)); /* remove value ... */
removeentry(n); /* and remove entry from table */
}
}
}
}
void luaC_upvdeccount (lua_State *L, UpVal *uv) {
lua_assert(uv->refcount > 0);
uv->refcount--;
if (uv->refcount == 0 && !upisopen(uv))
luaM_free(L, uv);
}
static void freeLclosure (lua_State *L, LClosure *cl) {
int i;
for (i = 0; i < cl->nupvalues; i++) {
UpVal *uv = cl->upvals[i];
if (uv)
luaC_upvdeccount(L, uv);
}
luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
}
static void freeobj (lua_State *L, GCObject *o) {
switch (o->tt) {
case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
case LUA_TLCL: {
freeLclosure(L, gco2lcl(o));
break;
}
case LUA_TCCL: {
luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
break;
}
case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
case LUA_TSHRSTR:
luaS_remove(L, gco2ts(o)); /* remove it from hash table */
luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen));
break;
case LUA_TLNGSTR: {
luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen));
break;
}
default: lua_assert(0);
}
}
#define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM)
static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
/*
** sweep at most 'count' elements from a list of GCObjects erasing dead
** objects, where a dead object is one marked with the old (non current)
** white; change all non-dead objects back to white, preparing for next
** collection cycle. Return where to continue the traversal or NULL if
** list is finished.
*/
static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
global_State *g = G(L);
int ow = otherwhite(g);
int white = luaC_white(g); /* current white */
while (*p != NULL && count-- > 0) {
GCObject *curr = *p;
int marked = curr->marked;
if (isdeadm(ow, marked)) { /* is 'curr' dead? */
*p = curr->next; /* remove 'curr' from list */
freeobj(L, curr); /* erase 'curr' */
}
else { /* change mark to 'white' */
curr->marked = cast_byte((marked & maskcolors) | white);
p = &curr->next; /* go to next element */
}
}
return (*p == NULL) ? NULL : p;
}
/*
** sweep a list until a live object (or end of list)
*/
static GCObject **sweeptolive (lua_State *L, GCObject **p) {
GCObject **old = p;
do {
p = sweeplist(L, p, 1);
} while (p == old);
return p;
}
/* }====================================================== */
/*
** {======================================================
** Finalization
** =======================================================
*/
/*
** If possible, shrink string table
*/
static void checkSizes (lua_State *L, global_State *g) {
if (g->gckind != KGC_EMERGENCY) {
l_mem olddebt = g->GCdebt;
if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
luaS_resize(L, g->strt.size / 2); /* shrink it a little */
g->GCestimate += g->GCdebt - olddebt; /* update estimate */
}
}
static GCObject *udata2finalize (global_State *g) {
GCObject *o = g->tobefnz; /* get first element */
lua_assert(tofinalize(o));
g->tobefnz = o->next; /* remove it from 'tobefnz' list */
o->next = g->allgc; /* return it to 'allgc' list */
g->allgc = o;
resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */
if (issweepphase(g))
makewhite(g, o); /* "sweep" object */
return o;
}
static void dothecall (lua_State *L, void *ud) {
UNUSED(ud);
luaD_callnoyield(L, L->top - 2, 0);
}
static void GCTM (lua_State *L, int propagateerrors) {
global_State *g = G(L);
const TValue *tm;
TValue v;
setgcovalue(L, &v, udata2finalize(g));
tm = luaT_gettmbyobj(L, &v, TM_GC);
if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
int status;
lu_byte oldah = L->allowhook;
int running = g->gcrunning;
L->allowhook = 0; /* stop debug hooks during GC metamethod */
g->gcrunning = 0; /* avoid GC steps */
setobj2s(L, L->top, tm); /* push finalizer... */
setobj2s(L, L->top + 1, &v); /* ... and its argument */
L->top += 2; /* and (next line) call the finalizer */
status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
L->allowhook = oldah; /* restore hooks */
g->gcrunning = running; /* restore state */
if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
if (status == LUA_ERRRUN) { /* is there an error object? */
const char *msg = (ttisstring(L->top - 1))
? svalue(L->top - 1)
: "no message";
luaO_pushfstring(L, "error in __gc metamethod (%s)", msg);
status = LUA_ERRGCMM; /* error in __gc metamethod */
}
luaD_throw(L, status); /* re-throw error */
}
}
}
/*
** call a few (up to 'g->gcfinnum') finalizers
*/
static int runafewfinalizers (lua_State *L) {
global_State *g = G(L);
unsigned int i;
lua_assert(!g->tobefnz || g->gcfinnum > 0);
for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
GCTM(L, 1); /* call one finalizer */
g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
: g->gcfinnum * 2; /* else call a few more next time */
return i;
}
/*
** call all pending finalizers
*/
static void callallpendingfinalizers (lua_State *L) {
global_State *g = G(L);
while (g->tobefnz)
GCTM(L, 0);
}
/*
** find last 'next' field in list 'p' list (to add elements in its end)
*/
static GCObject **findlast (GCObject **p) {
while (*p != NULL)
p = &(*p)->next;
return p;
}
/*
** move all unreachable objects (or 'all' objects) that need
** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
*/
static void separatetobefnz (global_State *g, int all) {
GCObject *curr;
GCObject **p = &g->finobj;
GCObject **lastnext = findlast(&g->tobefnz);
while ((curr = *p) != NULL) { /* traverse all finalizable objects */
lua_assert(tofinalize(curr));
if (!(iswhite(curr) || all)) /* not being collected? */
p = &curr->next; /* don't bother with it */
else {
*p = curr->next; /* remove 'curr' from 'finobj' list */
curr->next = *lastnext; /* link at the end of 'tobefnz' list */
*lastnext = curr;
lastnext = &curr->next;
}
}
}
/*
** if object 'o' has a finalizer, remove it from 'allgc' list (must
** search the list to find it) and link it in 'finobj' list.
*/
void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
global_State *g = G(L);
if (tofinalize(o) || /* obj. is already marked... */
gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
return; /* nothing to be done */
else { /* move 'o' to 'finobj' list */
GCObject **p;
if (issweepphase(g)) {
makewhite(g, o); /* "sweep" object 'o' */
if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */
g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */
}
/* search for pointer pointing to 'o' */
for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
*p = o->next; /* remove 'o' from 'allgc' list */
o->next = g->finobj; /* link it in 'finobj' list */
g->finobj = o;
l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */
}
}
/* }====================================================== */
/*
** {======================================================
** GC control
** =======================================================
*/
/*
** Set a reasonable "time" to wait before starting a new GC cycle; cycle
** will start when memory use hits threshold. (Division by 'estimate'
** should be OK: it cannot be zero (because Lua cannot even start with
** less than PAUSEADJ bytes).
*/
static void setpause (global_State *g) {
l_mem threshold, debt;
l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */
lua_assert(estimate > 0);
threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
? estimate * g->gcpause /* no overflow */
: MAX_LMEM; /* overflow; truncate to maximum */
debt = gettotalbytes(g) - threshold;
luaE_setdebt(g, debt);
}
/*
** Enter first sweep phase.
** The call to 'sweeplist' tries to make pointer point to an object
** inside the list (instead of to the header), so that the real sweep do
** not need to skip objects created between "now" and the start of the
** real sweep.
*/
static void entersweep (lua_State *L) {
global_State *g = G(L);
g->gcstate = GCSswpallgc;
lua_assert(g->sweepgc == NULL);
g->sweepgc = sweeplist(L, &g->allgc, 1);
}
void luaC_freeallobjects (lua_State *L) {
global_State *g = G(L);
separatetobefnz(g, 1); /* separate all objects with finalizers */
lua_assert(g->finobj == NULL);
callallpendingfinalizers(L);
lua_assert(g->tobefnz == NULL);
g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
g->gckind = KGC_NORMAL;
sweepwholelist(L, &g->finobj);
sweepwholelist(L, &g->allgc);
sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
lua_assert(g->strt.nuse == 0);
}
static l_mem atomic (lua_State *L) {
global_State *g = G(L);
l_mem work;
GCObject *origweak, *origall;
GCObject *grayagain = g->grayagain; /* save original list */
lua_assert(g->ephemeron == NULL && g->weak == NULL);
lua_assert(!iswhite(g->mainthread));
g->gcstate = GCSinsideatomic;
g->GCmemtrav = 0; /* start counting work */
markobject(g, L); /* mark running thread */
/* registry and global metatables may be changed by API */
markvalue(g, &g->l_registry);
markmt(g); /* mark global metatables */
/* remark occasional upvalues of (maybe) dead threads */
remarkupvals(g);
propagateall(g); /* propagate changes */
work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */
g->gray = grayagain;
propagateall(g); /* traverse 'grayagain' list */
g->GCmemtrav = 0; /* restart counting */
convergeephemerons(g);
/* at this point, all strongly accessible objects are marked. */
/* Clear values from weak tables, before checking finalizers */
clearvalues(g, g->weak, NULL);
clearvalues(g, g->allweak, NULL);
origweak = g->weak; origall = g->allweak;
work += g->GCmemtrav; /* stop counting (objects being finalized) */
separatetobefnz(g, 0); /* separate objects to be finalized */
g->gcfinnum = 1; /* there may be objects to be finalized */
markbeingfnz(g); /* mark objects that will be finalized */
propagateall(g); /* remark, to propagate 'resurrection' */
g->GCmemtrav = 0; /* restart counting */
convergeephemerons(g);
/* at this point, all resurrected objects are marked. */
/* remove dead objects from weak tables */
clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */
clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */
/* clear values from resurrected weak tables */
clearvalues(g, g->weak, origweak);
clearvalues(g, g->allweak, origall);
luaS_clearcache(g);
g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
work += g->GCmemtrav; /* complete counting */
return work; /* estimate of memory marked by 'atomic' */
}
static lu_mem sweepstep (lua_State *L, global_State *g,
int nextstate, GCObject **nextlist) {
if (g->sweepgc) {
l_mem olddebt = g->GCdebt;
g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
g->GCestimate += g->GCdebt - olddebt; /* update estimate */
if (g->sweepgc) /* is there still something to sweep? */
return (GCSWEEPMAX * GCSWEEPCOST);
}
/* else enter next state */
g->gcstate = nextstate;
g->sweepgc = nextlist;
return 0;
}
static lu_mem singlestep (lua_State *L) {
global_State *g = G(L);
switch (g->gcstate) {
case GCSpause: {
g->GCmemtrav = g->strt.size * sizeof(GCObject*);
restartcollection(g);
g->gcstate = GCSpropagate;
return g->GCmemtrav;
}
case GCSpropagate: {
g->GCmemtrav = 0;
lua_assert(g->gray);
propagatemark(g);
if (g->gray == NULL) /* no more gray objects? */
g->gcstate = GCSatomic; /* finish propagate phase */
return g->GCmemtrav; /* memory traversed in this step */
}
case GCSatomic: {
lu_mem work;
propagateall(g); /* make sure gray list is empty */
work = atomic(L); /* work is what was traversed by 'atomic' */
entersweep(L);
g->GCestimate = gettotalbytes(g); /* first estimate */;
return work;
}
case GCSswpallgc: { /* sweep "regular" objects */
return sweepstep(L, g, GCSswpfinobj, &g->finobj);
}
case GCSswpfinobj: { /* sweep objects with finalizers */
return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
}
case GCSswptobefnz: { /* sweep objects to be finalized */
return sweepstep(L, g, GCSswpend, NULL);
}
case GCSswpend: { /* finish sweeps */
makewhite(g, g->mainthread); /* sweep main thread */
checkSizes(L, g);
g->gcstate = GCScallfin;
return 0;
}
case GCScallfin: { /* call remaining finalizers */
if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
int n = runafewfinalizers(L);
return (n * GCFINALIZECOST);
}
else { /* emergency mode or no more finalizers */
g->gcstate = GCSpause; /* finish collection */
return 0;
}
}
default: lua_assert(0); return 0;
}
}
/*
** advances the garbage collector until it reaches a state allowed
** by 'statemask'
*/
void luaC_runtilstate (lua_State *L, int statesmask) {
global_State *g = G(L);
while (!testbit(statesmask, g->gcstate))
singlestep(L);
}
/*
** get GC debt and convert it from Kb to 'work units' (avoid zero debt
** and overflows)
*/
static l_mem getdebt (global_State *g) {
l_mem debt = g->GCdebt;
int stepmul = g->gcstepmul;
if (debt <= 0) return 0; /* minimal debt */
else {
debt = (debt / STEPMULADJ) + 1;
debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
return debt;
}
}
/*
** performs a basic GC step when collector is running
*/
void luaC_step (lua_State *L) {
global_State *g = G(L);
l_mem debt = getdebt(g); /* GC deficit (be paid now) */
if (!g->gcrunning) { /* not running? */
luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
return;
}
do { /* repeat until pause or enough "credit" (negative debt) */
lu_mem work = singlestep(L); /* perform one single step */
debt -= work;
} while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
if (g->gcstate == GCSpause)
setpause(g); /* pause until next cycle */
else {
debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
luaE_setdebt(g, debt);
runafewfinalizers(L);
}
}
/*
** Performs a full GC cycle; if 'isemergency', set a flag to avoid
** some operations which could change the interpreter state in some
** unexpected ways (running finalizers and shrinking some structures).
** Before running the collection, check 'keepinvariant'; if it is true,
** there may be some objects marked as black, so the collector has
** to sweep all objects to turn them back to white (as white has not
** changed, nothing will be collected).
*/
void luaC_fullgc (lua_State *L, int isemergency) {
global_State *g = G(L);
lua_assert(g->gckind == KGC_NORMAL);
if (isemergency) g->gckind = KGC_EMERGENCY; /* set flag */
if (keepinvariant(g)) { /* black objects? */
entersweep(L); /* sweep everything to turn them back to white */
}
/* finish any pending sweep phase to start a new cycle */
luaC_runtilstate(L, bitmask(GCSpause));
luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */
/* estimate must be correct after a full GC cycle */
lua_assert(g->GCestimate == gettotalbytes(g));
luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */
g->gckind = KGC_NORMAL;
setpause(g);
}
/* }====================================================== */
| xLua/build/lua-5.3.3/src/lgc.c/0 | {
"file_path": "xLua/build/lua-5.3.3/src/lgc.c",
"repo_id": "xLua",
"token_count": 14303
} | 2,086 |
/*
** $Id: loslib.c,v 1.64 2016/04/18 13:06:55 roberto Exp $
** Standard Operating System library
** See Copyright Notice in lua.h
*/
#define loslib_c
#define LUA_LIB
#include "lprefix.h"
#include <errno.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** {==================================================================
** List of valid conversion specifiers for the 'strftime' function;
** options are grouped by length; group of length 2 start with '||'.
** ===================================================================
*/
#if !defined(LUA_STRFTIMEOPTIONS) /* { */
/* options for ANSI C 89 */
#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%"
/* options for ISO C 99 and POSIX */
#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
"||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy"
/* options for Windows */
#define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \
"||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y"
#if defined(LUA_USE_WINDOWS)
#define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN
#elif defined(LUA_USE_C89)
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC89
#else /* C99 specification */
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC99
#endif
#endif /* } */
/* }================================================================== */
/*
** {==================================================================
** Configuration for time-related stuff
** ===================================================================
*/
#if !defined(l_time_t) /* { */
/*
** type to represent time_t in Lua
*/
#define l_timet lua_Integer
#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
static time_t l_checktime (lua_State *L, int arg) {
lua_Integer t = luaL_checkinteger(L, arg);
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
return (time_t)t;
}
#endif /* } */
#if !defined(l_gmtime) /* { */
/*
** By default, Lua uses gmtime/localtime, except when POSIX is available,
** where it uses gmtime_r/localtime_r
*/
#if defined(LUA_USE_POSIX) /* { */
#define l_gmtime(t,r) gmtime_r(t,r)
#define l_localtime(t,r) localtime_r(t,r)
#else /* }{ */
/* ISO C definitions */
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
#endif /* } */
#endif /* } */
/* }================================================================== */
/*
** {==================================================================
** Configuration for 'tmpnam':
** By default, Lua uses tmpnam except when POSIX is available, where
** it uses mkstemp.
** ===================================================================
*/
#if !defined(lua_tmpnam) /* { */
#if defined(LUA_USE_POSIX) /* { */
#include <unistd.h>
#define LUA_TMPNAMBUFSIZE 32
#if !defined(LUA_TMPNAMTEMPLATE)
#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX"
#endif
#define lua_tmpnam(b,e) { \
strcpy(b, LUA_TMPNAMTEMPLATE); \
e = mkstemp(b); \
if (e != -1) close(e); \
e = (e == -1); }
#else /* }{ */
/* ISO C definitions */
#define LUA_TMPNAMBUFSIZE L_tmpnam
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
#endif /* } */
#endif /* } */
/* }================================================================== */
static int os_execute (lua_State *L) {
#if defined(WINAPI_FAMILY_PARTITION)
return luaL_error(L, "unsupport api in uwp platform");
#else
const char *cmd = luaL_optstring(L, 1, NULL);
int stat = system(cmd);
if (cmd != NULL)
return luaL_execresult(L, stat);
else {
lua_pushboolean(L, stat); /* true if there is a shell */
return 1;
}
#endif
}
static int os_remove (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
return luaL_fileresult(L, remove(filename) == 0, filename);
}
static int os_rename (lua_State *L) {
const char *fromname = luaL_checkstring(L, 1);
const char *toname = luaL_checkstring(L, 2);
return luaL_fileresult(L, rename(fromname, toname) == 0, NULL);
}
static int os_tmpname (lua_State *L) {
char buff[LUA_TMPNAMBUFSIZE];
int err;
lua_tmpnam(buff, err);
if (err)
return luaL_error(L, "unable to generate a unique filename");
lua_pushstring(L, buff);
return 1;
}
static int os_getenv (lua_State *L) {
#if defined(WINAPI_FAMILY_PARTITION)
return luaL_error(L, "unsupport api in uwp platform");
#else
lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
return 1;
#endif
}
static int os_clock (lua_State *L) {
lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
return 1;
}
/*
** {======================================================
** Time/Date operations
** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
** wday=%w+1, yday=%j, isdst=? }
** =======================================================
*/
static void setfield (lua_State *L, const char *key, int value) {
lua_pushinteger(L, value);
lua_setfield(L, -2, key);
}
static void setboolfield (lua_State *L, const char *key, int value) {
if (value < 0) /* undefined? */
return; /* does not set field */
lua_pushboolean(L, value);
lua_setfield(L, -2, key);
}
/*
** Set all fields from structure 'tm' in the table on top of the stack
*/
static void setallfields (lua_State *L, struct tm *stm) {
setfield(L, "sec", stm->tm_sec);
setfield(L, "min", stm->tm_min);
setfield(L, "hour", stm->tm_hour);
setfield(L, "day", stm->tm_mday);
setfield(L, "month", stm->tm_mon + 1);
setfield(L, "year", stm->tm_year + 1900);
setfield(L, "wday", stm->tm_wday + 1);
setfield(L, "yday", stm->tm_yday + 1);
setboolfield(L, "isdst", stm->tm_isdst);
}
static int getboolfield (lua_State *L, const char *key) {
int res;
res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
lua_pop(L, 1);
return res;
}
/* maximum value for date fields (to avoid arithmetic overflows with 'int') */
#if !defined(L_MAXDATEFIELD)
#define L_MAXDATEFIELD (INT_MAX / 2)
#endif
static int getfield (lua_State *L, const char *key, int d, int delta) {
int isnum;
int t = lua_getfield(L, -1, key); /* get field and its type */
lua_Integer res = lua_tointegerx(L, -1, &isnum);
if (!isnum) { /* field is not an integer? */
if (t != LUA_TNIL) /* some other value? */
return luaL_error(L, "field '%s' is not an integer", key);
else if (d < 0) /* absent field; no default? */
return luaL_error(L, "field '%s' missing in date table", key);
res = d;
}
else {
if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))
return luaL_error(L, "field '%s' is out-of-bound", key);
res -= delta;
}
lua_pop(L, 1);
return (int)res;
}
static const char *checkoption (lua_State *L, const char *conv, char *buff) {
const char *option;
int oplen = 1;
for (option = LUA_STRFTIMEOPTIONS; *option != '\0'; option += oplen) {
if (*option == '|') /* next block? */
oplen++; /* next length */
else if (memcmp(conv, option, oplen) == 0) { /* match? */
memcpy(buff, conv, oplen); /* copy valid option to buffer */
buff[oplen] = '\0';
return conv + oplen; /* return next item */
}
}
luaL_argerror(L, 1,
lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
return conv; /* to avoid warnings */
}
/* maximum size for an individual 'strftime' item */
#define SIZETIMEFMT 250
static int os_date (lua_State *L) {
const char *s = luaL_optstring(L, 1, "%c");
time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
struct tm tmr, *stm;
if (*s == '!') { /* UTC? */
stm = l_gmtime(&t, &tmr);
s++; /* skip '!' */
}
else
stm = l_localtime(&t, &tmr);
if (stm == NULL) /* invalid date? */
luaL_error(L, "time result cannot be represented in this installation");
if (strcmp(s, "*t") == 0) {
lua_createtable(L, 0, 9); /* 9 = number of fields */
setallfields(L, stm);
}
else {
char cc[4]; /* buffer for individual conversion specifiers */
luaL_Buffer b;
cc[0] = '%';
luaL_buffinit(L, &b);
while (*s) {
if (*s != '%') /* not a conversion specifier? */
luaL_addchar(&b, *s++);
else {
size_t reslen;
char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
s = checkoption(L, s + 1, cc + 1); /* copy specifier to 'cc' */
reslen = strftime(buff, SIZETIMEFMT, cc, stm);
luaL_addsize(&b, reslen);
}
}
luaL_pushresult(&b);
}
return 1;
}
static int os_time (lua_State *L) {
time_t t;
if (lua_isnoneornil(L, 1)) /* called without args? */
t = time(NULL); /* get current time */
else {
struct tm ts;
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1); /* make sure table is at the top */
ts.tm_sec = getfield(L, "sec", 0, 0);
ts.tm_min = getfield(L, "min", 0, 0);
ts.tm_hour = getfield(L, "hour", 12, 0);
ts.tm_mday = getfield(L, "day", -1, 0);
ts.tm_mon = getfield(L, "month", -1, 1);
ts.tm_year = getfield(L, "year", -1, 1900);
ts.tm_isdst = getboolfield(L, "isdst");
t = mktime(&ts);
setallfields(L, &ts); /* update fields with normalized values */
}
if (t != (time_t)(l_timet)t || t == (time_t)(-1))
luaL_error(L, "time result cannot be represented in this installation");
l_pushtime(L, t);
return 1;
}
static int os_difftime (lua_State *L) {
time_t t1 = l_checktime(L, 1);
time_t t2 = l_checktime(L, 2);
lua_pushnumber(L, (lua_Number)difftime(t1, t2));
return 1;
}
/* }====================================================== */
static int os_setlocale (lua_State *L) {
static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
LC_NUMERIC, LC_TIME};
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", NULL};
const char *l = luaL_optstring(L, 1, NULL);
int op = luaL_checkoption(L, 2, "all", catnames);
lua_pushstring(L, setlocale(cat[op], l));
return 1;
}
static int os_exit (lua_State *L) {
int status;
if (lua_isboolean(L, 1))
status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
else
status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
if (lua_toboolean(L, 2))
lua_close(L);
if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
return 0;
}
static const luaL_Reg syslib[] = {
{"clock", os_clock},
{"date", os_date},
{"difftime", os_difftime},
{"execute", os_execute},
{"exit", os_exit},
{"getenv", os_getenv},
{"remove", os_remove},
{"rename", os_rename},
{"setlocale", os_setlocale},
{"time", os_time},
{"tmpname", os_tmpname},
{NULL, NULL}
};
/* }====================================================== */
LUAMOD_API int luaopen_os (lua_State *L) {
luaL_newlib(L, syslib);
return 1;
}
| xLua/build/lua-5.3.3/src/loslib.c/0 | {
"file_path": "xLua/build/lua-5.3.3/src/loslib.c",
"repo_id": "xLua",
"token_count": 4507
} | 2,087 |
// lua.hpp
// Lua header files for C++
// <<extern "C">> not supplied automatically because Lua also compiles as C++
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
| xLua/build/lua-5.3.3/src/lua.hpp/0 | {
"file_path": "xLua/build/lua-5.3.3/src/lua.hpp",
"repo_id": "xLua",
"token_count": 73
} | 2,088 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Lua 5.3 Reference Manual - contents</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
<LINK REL="stylesheet" TYPE="text/css" HREF="index.css">
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>
<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A>
Lua 5.3 Reference Manual
</H1>
<P>
The reference manual is the official definition of the Lua language.
<BR>
For a complete introduction to Lua programming, see the book
<A HREF="http://www.lua.org/pil/">Programming in Lua</A>.
<DIV CLASS="menubar">
<A HREF="manual.html">start</A>
·
<A HREF="#contents">contents</A>
·
<A HREF="#index">index</A>
·
<A HREF="http://www.lua.org/manual/">other versions</A>
</DIV>
<P>
<SMALL>
Copyright © 2015–2017 Lua.org, PUC-Rio.
Freely available under the terms of the
<A HREF="http://www.lua.org/license.html">Lua license</A>.
</SMALL>
<H2><A NAME="contents">Contents</A></H2>
<UL CLASS="contents menubar">
<LI><A HREF="manual.html">1 – Introduction</A>
<P>
<LI><A HREF="manual.html#2">2 – Basic Concepts</A>
<UL>
<LI><A HREF="manual.html#2.1">2.1 – Values and Types</A>
<LI><A HREF="manual.html#2.2">2.2 – Environments and the Global Environment</A>
<LI><A HREF="manual.html#2.3">2.3 – Error Handling</A>
<LI><A HREF="manual.html#2.4">2.4 – Metatables and Metamethods</A>
<LI><A HREF="manual.html#2.5">2.5 – Garbage Collection</A>
<UL>
<LI><A HREF="manual.html#2.5.1">2.5.1 – Garbage-Collection Metamethods</A>
<LI><A HREF="manual.html#2.5.2">2.5.2 – Weak Tables</A>
</UL>
<LI><A HREF="manual.html#2.6">2.6 – Coroutines</A>
</UL>
<P>
<LI><A HREF="manual.html#3">3 – The Language</A>
<UL>
<LI><A HREF="manual.html#3.1">3.1 – Lexical Conventions</A>
<LI><A HREF="manual.html#3.2">3.2 – Variables</A>
<LI><A HREF="manual.html#3.3">3.3 – Statements</A>
<UL>
<LI><A HREF="manual.html#3.3.1">3.3.1 – Blocks</A>
<LI><A HREF="manual.html#3.3.2">3.3.2 – Chunks</A>
<LI><A HREF="manual.html#3.3.3">3.3.3 – Assignment</A>
<LI><A HREF="manual.html#3.3.4">3.3.4 – Control Structures</A>
<LI><A HREF="manual.html#3.3.5">3.3.5 – For Statement</A>
<LI><A HREF="manual.html#3.3.6">3.3.6 – Function Calls as Statements</A>
<LI><A HREF="manual.html#3.3.7">3.3.7 – Local Declarations</A>
</UL>
<LI><A HREF="manual.html#3.4">3.4 – Expressions</A>
<UL>
<LI><A HREF="manual.html#3.4.1">3.4.1 – Arithmetic Operators</A>
<LI><A HREF="manual.html#3.4.2">3.4.2 – Bitwise Operators</A>
<LI><A HREF="manual.html#3.4.3">3.4.3 – Coercions and Conversions</A>
<LI><A HREF="manual.html#3.4.4">3.4.4 – Relational Operators</A>
<LI><A HREF="manual.html#3.4.5">3.4.5 – Logical Operators</A>
<LI><A HREF="manual.html#3.4.6">3.4.6 – Concatenation</A>
<LI><A HREF="manual.html#3.4.7">3.4.7 – The Length Operator</A>
<LI><A HREF="manual.html#3.4.8">3.4.8 – Precedence</A>
<LI><A HREF="manual.html#3.4.9">3.4.9 – Table Constructors</A>
<LI><A HREF="manual.html#3.4.10">3.4.10 – Function Calls</A>
<LI><A HREF="manual.html#3.4.11">3.4.11 – Function Definitions</A>
</UL>
<LI><A HREF="manual.html#3.5">3.5 – Visibility Rules</A>
</UL>
<P>
<LI><A HREF="manual.html#4">4 – The Application Program Interface</A>
<UL>
<LI><A HREF="manual.html#4.1">4.1 – The Stack</A>
<LI><A HREF="manual.html#4.2">4.2 – Stack Size</A>
<LI><A HREF="manual.html#4.3">4.3 – Valid and Acceptable Indices</A>
<LI><A HREF="manual.html#4.4">4.4 – C Closures</A>
<LI><A HREF="manual.html#4.5">4.5 – Registry</A>
<LI><A HREF="manual.html#4.6">4.6 – Error Handling in C</A>
<LI><A HREF="manual.html#4.7">4.7 – Handling Yields in C</A>
<LI><A HREF="manual.html#4.8">4.8 – Functions and Types</A>
<LI><A HREF="manual.html#4.9">4.9 – The Debug Interface</A>
</UL>
<P>
<LI><A HREF="manual.html#5">5 – The Auxiliary Library</A>
<UL>
<LI><A HREF="manual.html#5.1">5.1 – Functions and Types</A>
</UL>
<P>
<LI><A HREF="manual.html#6">6 – Standard Libraries</A>
<UL>
<LI><A HREF="manual.html#6.1">6.1 – Basic Functions</A>
<LI><A HREF="manual.html#6.2">6.2 – Coroutine Manipulation</A>
<LI><A HREF="manual.html#6.3">6.3 – Modules</A>
<LI><A HREF="manual.html#6.4">6.4 – String Manipulation</A>
<UL>
<LI><A HREF="manual.html#6.4.1">6.4.1 – Patterns</A>
<LI><A HREF="manual.html#6.4.2">6.4.2 – Format Strings for Pack and Unpack</A>
</UL>
<LI><A HREF="manual.html#6.5">6.5 – UTF-8 Support</A>
<LI><A HREF="manual.html#6.6">6.6 – Table Manipulation</A>
<LI><A HREF="manual.html#6.7">6.7 – Mathematical Functions</A>
<LI><A HREF="manual.html#6.8">6.8 – Input and Output Facilities</A>
<LI><A HREF="manual.html#6.9">6.9 – Operating System Facilities</A>
<LI><A HREF="manual.html#6.10">6.10 – The Debug Library</A>
</UL>
<P>
<LI><A HREF="manual.html#7">7 – Lua Standalone</A>
<P>
<LI><A HREF="manual.html#8">8 – Incompatibilities with the Previous Version</A>
<UL>
<LI><A HREF="manual.html#8.1">8.1 – Changes in the Language</A>
<LI><A HREF="manual.html#8.2">8.2 – Changes in the Libraries</A>
<LI><A HREF="manual.html#8.3">8.3 – Changes in the API</A>
</UL>
<P>
<LI><A HREF="manual.html#9">9 – The Complete Syntax of Lua</A>
</UL>
<H2><A NAME="index">Index</A></H2>
<TABLE CLASS="menubar" WIDTH="100%">
<TR>
<TD>
<H3><A NAME="functions">Lua functions</A></H3>
<P>
<A HREF="manual.html#6.1">basic</A><BR>
<A HREF="manual.html#pdf-_G">_G</A><BR>
<A HREF="manual.html#pdf-_VERSION">_VERSION</A><BR>
<A HREF="manual.html#pdf-assert">assert</A><BR>
<A HREF="manual.html#pdf-collectgarbage">collectgarbage</A><BR>
<A HREF="manual.html#pdf-dofile">dofile</A><BR>
<A HREF="manual.html#pdf-error">error</A><BR>
<A HREF="manual.html#pdf-getmetatable">getmetatable</A><BR>
<A HREF="manual.html#pdf-ipairs">ipairs</A><BR>
<A HREF="manual.html#pdf-load">load</A><BR>
<A HREF="manual.html#pdf-loadfile">loadfile</A><BR>
<A HREF="manual.html#pdf-next">next</A><BR>
<A HREF="manual.html#pdf-pairs">pairs</A><BR>
<A HREF="manual.html#pdf-pcall">pcall</A><BR>
<A HREF="manual.html#pdf-print">print</A><BR>
<A HREF="manual.html#pdf-rawequal">rawequal</A><BR>
<A HREF="manual.html#pdf-rawget">rawget</A><BR>
<A HREF="manual.html#pdf-rawlen">rawlen</A><BR>
<A HREF="manual.html#pdf-rawset">rawset</A><BR>
<A HREF="manual.html#pdf-require">require</A><BR>
<A HREF="manual.html#pdf-select">select</A><BR>
<A HREF="manual.html#pdf-setmetatable">setmetatable</A><BR>
<A HREF="manual.html#pdf-tonumber">tonumber</A><BR>
<A HREF="manual.html#pdf-tostring">tostring</A><BR>
<A HREF="manual.html#pdf-type">type</A><BR>
<A HREF="manual.html#pdf-xpcall">xpcall</A><BR>
<P>
<A HREF="manual.html#6.2">coroutine</A><BR>
<A HREF="manual.html#pdf-coroutine.create">coroutine.create</A><BR>
<A HREF="manual.html#pdf-coroutine.isyieldable">coroutine.isyieldable</A><BR>
<A HREF="manual.html#pdf-coroutine.resume">coroutine.resume</A><BR>
<A HREF="manual.html#pdf-coroutine.running">coroutine.running</A><BR>
<A HREF="manual.html#pdf-coroutine.status">coroutine.status</A><BR>
<A HREF="manual.html#pdf-coroutine.wrap">coroutine.wrap</A><BR>
<A HREF="manual.html#pdf-coroutine.yield">coroutine.yield</A><BR>
<P>
<A HREF="manual.html#6.10">debug</A><BR>
<A HREF="manual.html#pdf-debug.debug">debug.debug</A><BR>
<A HREF="manual.html#pdf-debug.gethook">debug.gethook</A><BR>
<A HREF="manual.html#pdf-debug.getinfo">debug.getinfo</A><BR>
<A HREF="manual.html#pdf-debug.getlocal">debug.getlocal</A><BR>
<A HREF="manual.html#pdf-debug.getmetatable">debug.getmetatable</A><BR>
<A HREF="manual.html#pdf-debug.getregistry">debug.getregistry</A><BR>
<A HREF="manual.html#pdf-debug.getupvalue">debug.getupvalue</A><BR>
<A HREF="manual.html#pdf-debug.getuservalue">debug.getuservalue</A><BR>
<A HREF="manual.html#pdf-debug.sethook">debug.sethook</A><BR>
<A HREF="manual.html#pdf-debug.setlocal">debug.setlocal</A><BR>
<A HREF="manual.html#pdf-debug.setmetatable">debug.setmetatable</A><BR>
<A HREF="manual.html#pdf-debug.setupvalue">debug.setupvalue</A><BR>
<A HREF="manual.html#pdf-debug.setuservalue">debug.setuservalue</A><BR>
<A HREF="manual.html#pdf-debug.traceback">debug.traceback</A><BR>
<A HREF="manual.html#pdf-debug.upvalueid">debug.upvalueid</A><BR>
<A HREF="manual.html#pdf-debug.upvaluejoin">debug.upvaluejoin</A><BR>
<P>
<A HREF="manual.html#6.8">io</A><BR>
<A HREF="manual.html#pdf-io.close">io.close</A><BR>
<A HREF="manual.html#pdf-io.flush">io.flush</A><BR>
<A HREF="manual.html#pdf-io.input">io.input</A><BR>
<A HREF="manual.html#pdf-io.lines">io.lines</A><BR>
<A HREF="manual.html#pdf-io.open">io.open</A><BR>
<A HREF="manual.html#pdf-io.output">io.output</A><BR>
<A HREF="manual.html#pdf-io.popen">io.popen</A><BR>
<A HREF="manual.html#pdf-io.read">io.read</A><BR>
<A HREF="manual.html#pdf-io.stderr">io.stderr</A><BR>
<A HREF="manual.html#pdf-io.stdin">io.stdin</A><BR>
<A HREF="manual.html#pdf-io.stdout">io.stdout</A><BR>
<A HREF="manual.html#pdf-io.tmpfile">io.tmpfile</A><BR>
<A HREF="manual.html#pdf-io.type">io.type</A><BR>
<A HREF="manual.html#pdf-io.write">io.write</A><BR>
<A HREF="manual.html#pdf-file:close">file:close</A><BR>
<A HREF="manual.html#pdf-file:flush">file:flush</A><BR>
<A HREF="manual.html#pdf-file:lines">file:lines</A><BR>
<A HREF="manual.html#pdf-file:read">file:read</A><BR>
<A HREF="manual.html#pdf-file:seek">file:seek</A><BR>
<A HREF="manual.html#pdf-file:setvbuf">file:setvbuf</A><BR>
<A HREF="manual.html#pdf-file:write">file:write</A><BR>
</TD>
<TD>
<H3> </H3>
<P>
<A HREF="manual.html#6.7">math</A><BR>
<A HREF="manual.html#pdf-math.abs">math.abs</A><BR>
<A HREF="manual.html#pdf-math.acos">math.acos</A><BR>
<A HREF="manual.html#pdf-math.asin">math.asin</A><BR>
<A HREF="manual.html#pdf-math.atan">math.atan</A><BR>
<A HREF="manual.html#pdf-math.ceil">math.ceil</A><BR>
<A HREF="manual.html#pdf-math.cos">math.cos</A><BR>
<A HREF="manual.html#pdf-math.deg">math.deg</A><BR>
<A HREF="manual.html#pdf-math.exp">math.exp</A><BR>
<A HREF="manual.html#pdf-math.floor">math.floor</A><BR>
<A HREF="manual.html#pdf-math.fmod">math.fmod</A><BR>
<A HREF="manual.html#pdf-math.huge">math.huge</A><BR>
<A HREF="manual.html#pdf-math.log">math.log</A><BR>
<A HREF="manual.html#pdf-math.max">math.max</A><BR>
<A HREF="manual.html#pdf-math.maxinteger">math.maxinteger</A><BR>
<A HREF="manual.html#pdf-math.min">math.min</A><BR>
<A HREF="manual.html#pdf-math.mininteger">math.mininteger</A><BR>
<A HREF="manual.html#pdf-math.modf">math.modf</A><BR>
<A HREF="manual.html#pdf-math.pi">math.pi</A><BR>
<A HREF="manual.html#pdf-math.rad">math.rad</A><BR>
<A HREF="manual.html#pdf-math.random">math.random</A><BR>
<A HREF="manual.html#pdf-math.randomseed">math.randomseed</A><BR>
<A HREF="manual.html#pdf-math.sin">math.sin</A><BR>
<A HREF="manual.html#pdf-math.sqrt">math.sqrt</A><BR>
<A HREF="manual.html#pdf-math.tan">math.tan</A><BR>
<A HREF="manual.html#pdf-math.tointeger">math.tointeger</A><BR>
<A HREF="manual.html#pdf-math.type">math.type</A><BR>
<A HREF="manual.html#pdf-math.ult">math.ult</A><BR>
<P>
<A HREF="manual.html#6.9">os</A><BR>
<A HREF="manual.html#pdf-os.clock">os.clock</A><BR>
<A HREF="manual.html#pdf-os.date">os.date</A><BR>
<A HREF="manual.html#pdf-os.difftime">os.difftime</A><BR>
<A HREF="manual.html#pdf-os.execute">os.execute</A><BR>
<A HREF="manual.html#pdf-os.exit">os.exit</A><BR>
<A HREF="manual.html#pdf-os.getenv">os.getenv</A><BR>
<A HREF="manual.html#pdf-os.remove">os.remove</A><BR>
<A HREF="manual.html#pdf-os.rename">os.rename</A><BR>
<A HREF="manual.html#pdf-os.setlocale">os.setlocale</A><BR>
<A HREF="manual.html#pdf-os.time">os.time</A><BR>
<A HREF="manual.html#pdf-os.tmpname">os.tmpname</A><BR>
<P>
<A HREF="manual.html#6.3">package</A><BR>
<A HREF="manual.html#pdf-package.config">package.config</A><BR>
<A HREF="manual.html#pdf-package.cpath">package.cpath</A><BR>
<A HREF="manual.html#pdf-package.loaded">package.loaded</A><BR>
<A HREF="manual.html#pdf-package.loadlib">package.loadlib</A><BR>
<A HREF="manual.html#pdf-package.path">package.path</A><BR>
<A HREF="manual.html#pdf-package.preload">package.preload</A><BR>
<A HREF="manual.html#pdf-package.searchers">package.searchers</A><BR>
<A HREF="manual.html#pdf-package.searchpath">package.searchpath</A><BR>
<P>
<A HREF="manual.html#6.4">string</A><BR>
<A HREF="manual.html#pdf-string.byte">string.byte</A><BR>
<A HREF="manual.html#pdf-string.char">string.char</A><BR>
<A HREF="manual.html#pdf-string.dump">string.dump</A><BR>
<A HREF="manual.html#pdf-string.find">string.find</A><BR>
<A HREF="manual.html#pdf-string.format">string.format</A><BR>
<A HREF="manual.html#pdf-string.gmatch">string.gmatch</A><BR>
<A HREF="manual.html#pdf-string.gsub">string.gsub</A><BR>
<A HREF="manual.html#pdf-string.len">string.len</A><BR>
<A HREF="manual.html#pdf-string.lower">string.lower</A><BR>
<A HREF="manual.html#pdf-string.match">string.match</A><BR>
<A HREF="manual.html#pdf-string.pack">string.pack</A><BR>
<A HREF="manual.html#pdf-string.packsize">string.packsize</A><BR>
<A HREF="manual.html#pdf-string.rep">string.rep</A><BR>
<A HREF="manual.html#pdf-string.reverse">string.reverse</A><BR>
<A HREF="manual.html#pdf-string.sub">string.sub</A><BR>
<A HREF="manual.html#pdf-string.unpack">string.unpack</A><BR>
<A HREF="manual.html#pdf-string.upper">string.upper</A><BR>
<P>
<A HREF="manual.html#6.6">table</A><BR>
<A HREF="manual.html#pdf-table.concat">table.concat</A><BR>
<A HREF="manual.html#pdf-table.insert">table.insert</A><BR>
<A HREF="manual.html#pdf-table.move">table.move</A><BR>
<A HREF="manual.html#pdf-table.pack">table.pack</A><BR>
<A HREF="manual.html#pdf-table.remove">table.remove</A><BR>
<A HREF="manual.html#pdf-table.sort">table.sort</A><BR>
<A HREF="manual.html#pdf-table.unpack">table.unpack</A><BR>
<P>
<A HREF="manual.html#6.5">utf8</A><BR>
<A HREF="manual.html#pdf-utf8.char">utf8.char</A><BR>
<A HREF="manual.html#pdf-utf8.charpattern">utf8.charpattern</A><BR>
<A HREF="manual.html#pdf-utf8.codepoint">utf8.codepoint</A><BR>
<A HREF="manual.html#pdf-utf8.codes">utf8.codes</A><BR>
<A HREF="manual.html#pdf-utf8.len">utf8.len</A><BR>
<A HREF="manual.html#pdf-utf8.offset">utf8.offset</A><BR>
<H3><A NAME="env">environment<BR>variables</A></H3>
<P>
<A HREF="manual.html#pdf-LUA_CPATH">LUA_CPATH</A><BR>
<A HREF="manual.html#pdf-LUA_CPATH_5_3">LUA_CPATH_5_3</A><BR>
<A HREF="manual.html#pdf-LUA_INIT">LUA_INIT</A><BR>
<A HREF="manual.html#pdf-LUA_INIT_5_3">LUA_INIT_5_3</A><BR>
<A HREF="manual.html#pdf-LUA_PATH">LUA_PATH</A><BR>
<A HREF="manual.html#pdf-LUA_PATH_5_3">LUA_PATH_5_3</A><BR>
</TD>
<TD>
<H3><A NAME="api">C API</A></H3>
<P>
<A HREF="manual.html#lua_Alloc">lua_Alloc</A><BR>
<A HREF="manual.html#lua_CFunction">lua_CFunction</A><BR>
<A HREF="manual.html#lua_Debug">lua_Debug</A><BR>
<A HREF="manual.html#lua_Hook">lua_Hook</A><BR>
<A HREF="manual.html#lua_Integer">lua_Integer</A><BR>
<A HREF="manual.html#lua_KContext">lua_KContext</A><BR>
<A HREF="manual.html#lua_KFunction">lua_KFunction</A><BR>
<A HREF="manual.html#lua_Number">lua_Number</A><BR>
<A HREF="manual.html#lua_Reader">lua_Reader</A><BR>
<A HREF="manual.html#lua_State">lua_State</A><BR>
<A HREF="manual.html#lua_Unsigned">lua_Unsigned</A><BR>
<A HREF="manual.html#lua_Writer">lua_Writer</A><BR>
<P>
<A HREF="manual.html#lua_absindex">lua_absindex</A><BR>
<A HREF="manual.html#lua_arith">lua_arith</A><BR>
<A HREF="manual.html#lua_atpanic">lua_atpanic</A><BR>
<A HREF="manual.html#lua_call">lua_call</A><BR>
<A HREF="manual.html#lua_callk">lua_callk</A><BR>
<A HREF="manual.html#lua_checkstack">lua_checkstack</A><BR>
<A HREF="manual.html#lua_close">lua_close</A><BR>
<A HREF="manual.html#lua_compare">lua_compare</A><BR>
<A HREF="manual.html#lua_concat">lua_concat</A><BR>
<A HREF="manual.html#lua_copy">lua_copy</A><BR>
<A HREF="manual.html#lua_createtable">lua_createtable</A><BR>
<A HREF="manual.html#lua_dump">lua_dump</A><BR>
<A HREF="manual.html#lua_error">lua_error</A><BR>
<A HREF="manual.html#lua_gc">lua_gc</A><BR>
<A HREF="manual.html#lua_getallocf">lua_getallocf</A><BR>
<A HREF="manual.html#lua_getextraspace">lua_getextraspace</A><BR>
<A HREF="manual.html#lua_getfield">lua_getfield</A><BR>
<A HREF="manual.html#lua_getglobal">lua_getglobal</A><BR>
<A HREF="manual.html#lua_gethook">lua_gethook</A><BR>
<A HREF="manual.html#lua_gethookcount">lua_gethookcount</A><BR>
<A HREF="manual.html#lua_gethookmask">lua_gethookmask</A><BR>
<A HREF="manual.html#lua_geti">lua_geti</A><BR>
<A HREF="manual.html#lua_getinfo">lua_getinfo</A><BR>
<A HREF="manual.html#lua_getlocal">lua_getlocal</A><BR>
<A HREF="manual.html#lua_getmetatable">lua_getmetatable</A><BR>
<A HREF="manual.html#lua_getstack">lua_getstack</A><BR>
<A HREF="manual.html#lua_gettable">lua_gettable</A><BR>
<A HREF="manual.html#lua_gettop">lua_gettop</A><BR>
<A HREF="manual.html#lua_getupvalue">lua_getupvalue</A><BR>
<A HREF="manual.html#lua_getuservalue">lua_getuservalue</A><BR>
<A HREF="manual.html#lua_insert">lua_insert</A><BR>
<A HREF="manual.html#lua_isboolean">lua_isboolean</A><BR>
<A HREF="manual.html#lua_iscfunction">lua_iscfunction</A><BR>
<A HREF="manual.html#lua_isfunction">lua_isfunction</A><BR>
<A HREF="manual.html#lua_isinteger">lua_isinteger</A><BR>
<A HREF="manual.html#lua_islightuserdata">lua_islightuserdata</A><BR>
<A HREF="manual.html#lua_isnil">lua_isnil</A><BR>
<A HREF="manual.html#lua_isnone">lua_isnone</A><BR>
<A HREF="manual.html#lua_isnoneornil">lua_isnoneornil</A><BR>
<A HREF="manual.html#lua_isnumber">lua_isnumber</A><BR>
<A HREF="manual.html#lua_isstring">lua_isstring</A><BR>
<A HREF="manual.html#lua_istable">lua_istable</A><BR>
<A HREF="manual.html#lua_isthread">lua_isthread</A><BR>
<A HREF="manual.html#lua_isuserdata">lua_isuserdata</A><BR>
<A HREF="manual.html#lua_isyieldable">lua_isyieldable</A><BR>
<A HREF="manual.html#lua_len">lua_len</A><BR>
<A HREF="manual.html#lua_load">lua_load</A><BR>
<A HREF="manual.html#lua_newstate">lua_newstate</A><BR>
<A HREF="manual.html#lua_newtable">lua_newtable</A><BR>
<A HREF="manual.html#lua_newthread">lua_newthread</A><BR>
<A HREF="manual.html#lua_newuserdata">lua_newuserdata</A><BR>
<A HREF="manual.html#lua_next">lua_next</A><BR>
<A HREF="manual.html#lua_numbertointeger">lua_numbertointeger</A><BR>
<A HREF="manual.html#lua_pcall">lua_pcall</A><BR>
<A HREF="manual.html#lua_pcallk">lua_pcallk</A><BR>
<A HREF="manual.html#lua_pop">lua_pop</A><BR>
<A HREF="manual.html#lua_pushboolean">lua_pushboolean</A><BR>
<A HREF="manual.html#lua_pushcclosure">lua_pushcclosure</A><BR>
<A HREF="manual.html#lua_pushcfunction">lua_pushcfunction</A><BR>
<A HREF="manual.html#lua_pushfstring">lua_pushfstring</A><BR>
<A HREF="manual.html#lua_pushglobaltable">lua_pushglobaltable</A><BR>
<A HREF="manual.html#lua_pushinteger">lua_pushinteger</A><BR>
<A HREF="manual.html#lua_pushlightuserdata">lua_pushlightuserdata</A><BR>
<A HREF="manual.html#lua_pushliteral">lua_pushliteral</A><BR>
<A HREF="manual.html#lua_pushlstring">lua_pushlstring</A><BR>
<A HREF="manual.html#lua_pushnil">lua_pushnil</A><BR>
<A HREF="manual.html#lua_pushnumber">lua_pushnumber</A><BR>
<A HREF="manual.html#lua_pushstring">lua_pushstring</A><BR>
<A HREF="manual.html#lua_pushthread">lua_pushthread</A><BR>
<A HREF="manual.html#lua_pushvalue">lua_pushvalue</A><BR>
<A HREF="manual.html#lua_pushvfstring">lua_pushvfstring</A><BR>
<A HREF="manual.html#lua_rawequal">lua_rawequal</A><BR>
<A HREF="manual.html#lua_rawget">lua_rawget</A><BR>
<A HREF="manual.html#lua_rawgeti">lua_rawgeti</A><BR>
<A HREF="manual.html#lua_rawgetp">lua_rawgetp</A><BR>
<A HREF="manual.html#lua_rawlen">lua_rawlen</A><BR>
<A HREF="manual.html#lua_rawset">lua_rawset</A><BR>
<A HREF="manual.html#lua_rawseti">lua_rawseti</A><BR>
<A HREF="manual.html#lua_rawsetp">lua_rawsetp</A><BR>
<A HREF="manual.html#lua_register">lua_register</A><BR>
<A HREF="manual.html#lua_remove">lua_remove</A><BR>
<A HREF="manual.html#lua_replace">lua_replace</A><BR>
<A HREF="manual.html#lua_resume">lua_resume</A><BR>
<A HREF="manual.html#lua_rotate">lua_rotate</A><BR>
<A HREF="manual.html#lua_setallocf">lua_setallocf</A><BR>
<A HREF="manual.html#lua_setfield">lua_setfield</A><BR>
<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
<A HREF="manual.html#lua_sethook">lua_sethook</A><BR>
<A HREF="manual.html#lua_seti">lua_seti</A><BR>
<A HREF="manual.html#lua_setlocal">lua_setlocal</A><BR>
<A HREF="manual.html#lua_setmetatable">lua_setmetatable</A><BR>
<A HREF="manual.html#lua_settable">lua_settable</A><BR>
<A HREF="manual.html#lua_settop">lua_settop</A><BR>
<A HREF="manual.html#lua_setupvalue">lua_setupvalue</A><BR>
<A HREF="manual.html#lua_setuservalue">lua_setuservalue</A><BR>
<A HREF="manual.html#lua_status">lua_status</A><BR>
<A HREF="manual.html#lua_stringtonumber">lua_stringtonumber</A><BR>
<A HREF="manual.html#lua_toboolean">lua_toboolean</A><BR>
<A HREF="manual.html#lua_tocfunction">lua_tocfunction</A><BR>
<A HREF="manual.html#lua_tointeger">lua_tointeger</A><BR>
<A HREF="manual.html#lua_tointegerx">lua_tointegerx</A><BR>
<A HREF="manual.html#lua_tolstring">lua_tolstring</A><BR>
<A HREF="manual.html#lua_tonumber">lua_tonumber</A><BR>
<A HREF="manual.html#lua_tonumberx">lua_tonumberx</A><BR>
<A HREF="manual.html#lua_topointer">lua_topointer</A><BR>
<A HREF="manual.html#lua_tostring">lua_tostring</A><BR>
<A HREF="manual.html#lua_tothread">lua_tothread</A><BR>
<A HREF="manual.html#lua_touserdata">lua_touserdata</A><BR>
<A HREF="manual.html#lua_type">lua_type</A><BR>
<A HREF="manual.html#lua_typename">lua_typename</A><BR>
<A HREF="manual.html#lua_upvalueid">lua_upvalueid</A><BR>
<A HREF="manual.html#lua_upvalueindex">lua_upvalueindex</A><BR>
<A HREF="manual.html#lua_upvaluejoin">lua_upvaluejoin</A><BR>
<A HREF="manual.html#lua_version">lua_version</A><BR>
<A HREF="manual.html#lua_xmove">lua_xmove</A><BR>
<A HREF="manual.html#lua_yield">lua_yield</A><BR>
<A HREF="manual.html#lua_yieldk">lua_yieldk</A><BR>
</TD>
<TD>
<H3><A NAME="auxlib">auxiliary library</A></H3>
<P>
<A HREF="manual.html#luaL_Buffer">luaL_Buffer</A><BR>
<A HREF="manual.html#luaL_Reg">luaL_Reg</A><BR>
<A HREF="manual.html#luaL_Stream">luaL_Stream</A><BR>
<P>
<A HREF="manual.html#luaL_addchar">luaL_addchar</A><BR>
<A HREF="manual.html#luaL_addlstring">luaL_addlstring</A><BR>
<A HREF="manual.html#luaL_addsize">luaL_addsize</A><BR>
<A HREF="manual.html#luaL_addstring">luaL_addstring</A><BR>
<A HREF="manual.html#luaL_addvalue">luaL_addvalue</A><BR>
<A HREF="manual.html#luaL_argcheck">luaL_argcheck</A><BR>
<A HREF="manual.html#luaL_argerror">luaL_argerror</A><BR>
<A HREF="manual.html#luaL_buffinit">luaL_buffinit</A><BR>
<A HREF="manual.html#luaL_buffinitsize">luaL_buffinitsize</A><BR>
<A HREF="manual.html#luaL_callmeta">luaL_callmeta</A><BR>
<A HREF="manual.html#luaL_checkany">luaL_checkany</A><BR>
<A HREF="manual.html#luaL_checkinteger">luaL_checkinteger</A><BR>
<A HREF="manual.html#luaL_checklstring">luaL_checklstring</A><BR>
<A HREF="manual.html#luaL_checknumber">luaL_checknumber</A><BR>
<A HREF="manual.html#luaL_checkoption">luaL_checkoption</A><BR>
<A HREF="manual.html#luaL_checkstack">luaL_checkstack</A><BR>
<A HREF="manual.html#luaL_checkstring">luaL_checkstring</A><BR>
<A HREF="manual.html#luaL_checktype">luaL_checktype</A><BR>
<A HREF="manual.html#luaL_checkudata">luaL_checkudata</A><BR>
<A HREF="manual.html#luaL_checkversion">luaL_checkversion</A><BR>
<A HREF="manual.html#luaL_dofile">luaL_dofile</A><BR>
<A HREF="manual.html#luaL_dostring">luaL_dostring</A><BR>
<A HREF="manual.html#luaL_error">luaL_error</A><BR>
<A HREF="manual.html#luaL_execresult">luaL_execresult</A><BR>
<A HREF="manual.html#luaL_fileresult">luaL_fileresult</A><BR>
<A HREF="manual.html#luaL_getmetafield">luaL_getmetafield</A><BR>
<A HREF="manual.html#luaL_getmetatable">luaL_getmetatable</A><BR>
<A HREF="manual.html#luaL_getsubtable">luaL_getsubtable</A><BR>
<A HREF="manual.html#luaL_gsub">luaL_gsub</A><BR>
<A HREF="manual.html#luaL_len">luaL_len</A><BR>
<A HREF="manual.html#luaL_loadbuffer">luaL_loadbuffer</A><BR>
<A HREF="manual.html#luaL_loadbufferx">luaL_loadbufferx</A><BR>
<A HREF="manual.html#luaL_loadfile">luaL_loadfile</A><BR>
<A HREF="manual.html#luaL_loadfilex">luaL_loadfilex</A><BR>
<A HREF="manual.html#luaL_loadstring">luaL_loadstring</A><BR>
<A HREF="manual.html#luaL_newlib">luaL_newlib</A><BR>
<A HREF="manual.html#luaL_newlibtable">luaL_newlibtable</A><BR>
<A HREF="manual.html#luaL_newmetatable">luaL_newmetatable</A><BR>
<A HREF="manual.html#luaL_newstate">luaL_newstate</A><BR>
<A HREF="manual.html#luaL_openlibs">luaL_openlibs</A><BR>
<A HREF="manual.html#luaL_opt">luaL_opt</A><BR>
<A HREF="manual.html#luaL_optinteger">luaL_optinteger</A><BR>
<A HREF="manual.html#luaL_optlstring">luaL_optlstring</A><BR>
<A HREF="manual.html#luaL_optnumber">luaL_optnumber</A><BR>
<A HREF="manual.html#luaL_optstring">luaL_optstring</A><BR>
<A HREF="manual.html#luaL_prepbuffer">luaL_prepbuffer</A><BR>
<A HREF="manual.html#luaL_prepbuffsize">luaL_prepbuffsize</A><BR>
<A HREF="manual.html#luaL_pushresult">luaL_pushresult</A><BR>
<A HREF="manual.html#luaL_pushresultsize">luaL_pushresultsize</A><BR>
<A HREF="manual.html#luaL_ref">luaL_ref</A><BR>
<A HREF="manual.html#luaL_requiref">luaL_requiref</A><BR>
<A HREF="manual.html#luaL_setfuncs">luaL_setfuncs</A><BR>
<A HREF="manual.html#luaL_setmetatable">luaL_setmetatable</A><BR>
<A HREF="manual.html#luaL_testudata">luaL_testudata</A><BR>
<A HREF="manual.html#luaL_tolstring">luaL_tolstring</A><BR>
<A HREF="manual.html#luaL_traceback">luaL_traceback</A><BR>
<A HREF="manual.html#luaL_typename">luaL_typename</A><BR>
<A HREF="manual.html#luaL_unref">luaL_unref</A><BR>
<A HREF="manual.html#luaL_where">luaL_where</A><BR>
<H3><A NAME="library">standard library</A></H3>
<P>
<A HREF="manual.html#pdf-luaopen_base">luaopen_base</A><BR>
<A HREF="manual.html#pdf-luaopen_coroutine">luaopen_coroutine</A><BR>
<A HREF="manual.html#pdf-luaopen_debug">luaopen_debug</A><BR>
<A HREF="manual.html#pdf-luaopen_io">luaopen_io</A><BR>
<A HREF="manual.html#pdf-luaopen_math">luaopen_math</A><BR>
<A HREF="manual.html#pdf-luaopen_os">luaopen_os</A><BR>
<A HREF="manual.html#pdf-luaopen_package">luaopen_package</A><BR>
<A HREF="manual.html#pdf-luaopen_string">luaopen_string</A><BR>
<A HREF="manual.html#pdf-luaopen_table">luaopen_table</A><BR>
<A HREF="manual.html#pdf-luaopen_utf8">luaopen_utf8</A><BR>
<H3><A NAME="constants">constants</A></H3>
<P>
<A HREF="manual.html#pdf-LUA_ERRERR">LUA_ERRERR</A><BR>
<A HREF="manual.html#pdf-LUA_ERRFILE">LUA_ERRFILE</A><BR>
<A HREF="manual.html#pdf-LUA_ERRGCMM">LUA_ERRGCMM</A><BR>
<A HREF="manual.html#pdf-LUA_ERRMEM">LUA_ERRMEM</A><BR>
<A HREF="manual.html#pdf-LUA_ERRRUN">LUA_ERRRUN</A><BR>
<A HREF="manual.html#pdf-LUA_ERRSYNTAX">LUA_ERRSYNTAX</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKCALL">LUA_HOOKCALL</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKCOUNT">LUA_HOOKCOUNT</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKLINE">LUA_HOOKLINE</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKRET">LUA_HOOKRET</A><BR>
<A HREF="manual.html#pdf-LUA_HOOKTAILCALL">LUA_HOOKTAILCALL</A><BR>
<A HREF="manual.html#pdf-LUA_MASKCALL">LUA_MASKCALL</A><BR>
<A HREF="manual.html#pdf-LUA_MASKCOUNT">LUA_MASKCOUNT</A><BR>
<A HREF="manual.html#pdf-LUA_MASKLINE">LUA_MASKLINE</A><BR>
<A HREF="manual.html#pdf-LUA_MASKRET">LUA_MASKRET</A><BR>
<A HREF="manual.html#pdf-LUA_MAXINTEGER">LUA_MAXINTEGER</A><BR>
<A HREF="manual.html#pdf-LUA_MININTEGER">LUA_MININTEGER</A><BR>
<A HREF="manual.html#pdf-LUA_MINSTACK">LUA_MINSTACK</A><BR>
<A HREF="manual.html#pdf-LUA_MULTRET">LUA_MULTRET</A><BR>
<A HREF="manual.html#pdf-LUA_NOREF">LUA_NOREF</A><BR>
<A HREF="manual.html#pdf-LUA_OK">LUA_OK</A><BR>
<A HREF="manual.html#pdf-LUA_OPADD">LUA_OPADD</A><BR>
<A HREF="manual.html#pdf-LUA_OPBAND">LUA_OPBAND</A><BR>
<A HREF="manual.html#pdf-LUA_OPBNOT">LUA_OPBNOT</A><BR>
<A HREF="manual.html#pdf-LUA_OPBOR">LUA_OPBOR</A><BR>
<A HREF="manual.html#pdf-LUA_OPBXOR">LUA_OPBXOR</A><BR>
<A HREF="manual.html#pdf-LUA_OPDIV">LUA_OPDIV</A><BR>
<A HREF="manual.html#pdf-LUA_OPEQ">LUA_OPEQ</A><BR>
<A HREF="manual.html#pdf-LUA_OPIDIV">LUA_OPIDIV</A><BR>
<A HREF="manual.html#pdf-LUA_OPLE">LUA_OPLE</A><BR>
<A HREF="manual.html#pdf-LUA_OPLT">LUA_OPLT</A><BR>
<A HREF="manual.html#pdf-LUA_OPMOD">LUA_OPMOD</A><BR>
<A HREF="manual.html#pdf-LUA_OPMUL">LUA_OPMUL</A><BR>
<A HREF="manual.html#pdf-LUA_OPPOW">LUA_OPPOW</A><BR>
<A HREF="manual.html#pdf-LUA_OPSHL">LUA_OPSHL</A><BR>
<A HREF="manual.html#pdf-LUA_OPSHR">LUA_OPSHR</A><BR>
<A HREF="manual.html#pdf-LUA_OPSUB">LUA_OPSUB</A><BR>
<A HREF="manual.html#pdf-LUA_OPUNM">LUA_OPUNM</A><BR>
<A HREF="manual.html#pdf-LUA_REFNIL">LUA_REFNIL</A><BR>
<A HREF="manual.html#pdf-LUA_REGISTRYINDEX">LUA_REGISTRYINDEX</A><BR>
<A HREF="manual.html#pdf-LUA_RIDX_GLOBALS">LUA_RIDX_GLOBALS</A><BR>
<A HREF="manual.html#pdf-LUA_RIDX_MAINTHREAD">LUA_RIDX_MAINTHREAD</A><BR>
<A HREF="manual.html#pdf-LUA_TBOOLEAN">LUA_TBOOLEAN</A><BR>
<A HREF="manual.html#pdf-LUA_TFUNCTION">LUA_TFUNCTION</A><BR>
<A HREF="manual.html#pdf-LUA_TLIGHTUSERDATA">LUA_TLIGHTUSERDATA</A><BR>
<A HREF="manual.html#pdf-LUA_TNIL">LUA_TNIL</A><BR>
<A HREF="manual.html#pdf-LUA_TNONE">LUA_TNONE</A><BR>
<A HREF="manual.html#pdf-LUA_TNUMBER">LUA_TNUMBER</A><BR>
<A HREF="manual.html#pdf-LUA_TSTRING">LUA_TSTRING</A><BR>
<A HREF="manual.html#pdf-LUA_TTABLE">LUA_TTABLE</A><BR>
<A HREF="manual.html#pdf-LUA_TTHREAD">LUA_TTHREAD</A><BR>
<A HREF="manual.html#pdf-LUA_TUSERDATA">LUA_TUSERDATA</A><BR>
<A HREF="manual.html#pdf-LUA_USE_APICHECK">LUA_USE_APICHECK</A><BR>
<A HREF="manual.html#pdf-LUA_YIELD">LUA_YIELD</A><BR>
<A HREF="manual.html#pdf-LUAL_BUFFERSIZE">LUAL_BUFFERSIZE</A><BR>
</TD>
</TR>
</TABLE>
<P CLASS="footer">
Last update:
Thu Dec 22 18:29:39 BRST 2016
</P>
<!--
Last change: revised for Lua 5.3.4
-->
</BODY>
</HTML>
| xLua/build/lua-5.3.4/doc/contents.html/0 | {
"file_path": "xLua/build/lua-5.3.4/doc/contents.html",
"repo_id": "xLua",
"token_count": 14093
} | 2,089 |
/*
** $Id: lbitlib.c,v 1.30 2015/11/11 19:08:09 roberto Exp $
** Standard library for bitwise operations
** See Copyright Notice in lua.h
*/
#define lbitlib_c
#define LUA_LIB
#include "lprefix.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#if defined(LUA_COMPAT_BITLIB) /* { */
#define pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
#define checkunsigned(L,i) ((lua_Unsigned)luaL_checkinteger(L,i))
/* number of bits to consider in a number */
#if !defined(LUA_NBITS)
#define LUA_NBITS 32
#endif
/*
** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must
** be made in two parts to avoid problems when LUA_NBITS is equal to the
** number of bits in a lua_Unsigned.)
*/
#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
/* macro to trim extra bits */
#define trim(x) ((x) & ALLONES)
/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */
#define mask(n) (~((ALLONES << 1) << ((n) - 1)))
static lua_Unsigned andaux (lua_State *L) {
int i, n = lua_gettop(L);
lua_Unsigned r = ~(lua_Unsigned)0;
for (i = 1; i <= n; i++)
r &= checkunsigned(L, i);
return trim(r);
}
static int b_and (lua_State *L) {
lua_Unsigned r = andaux(L);
pushunsigned(L, r);
return 1;
}
static int b_test (lua_State *L) {
lua_Unsigned r = andaux(L);
lua_pushboolean(L, r != 0);
return 1;
}
static int b_or (lua_State *L) {
int i, n = lua_gettop(L);
lua_Unsigned r = 0;
for (i = 1; i <= n; i++)
r |= checkunsigned(L, i);
pushunsigned(L, trim(r));
return 1;
}
static int b_xor (lua_State *L) {
int i, n = lua_gettop(L);
lua_Unsigned r = 0;
for (i = 1; i <= n; i++)
r ^= checkunsigned(L, i);
pushunsigned(L, trim(r));
return 1;
}
static int b_not (lua_State *L) {
lua_Unsigned r = ~checkunsigned(L, 1);
pushunsigned(L, trim(r));
return 1;
}
static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {
if (i < 0) { /* shift right? */
i = -i;
r = trim(r);
if (i >= LUA_NBITS) r = 0;
else r >>= i;
}
else { /* shift left */
if (i >= LUA_NBITS) r = 0;
else r <<= i;
r = trim(r);
}
pushunsigned(L, r);
return 1;
}
static int b_lshift (lua_State *L) {
return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2));
}
static int b_rshift (lua_State *L) {
return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2));
}
static int b_arshift (lua_State *L) {
lua_Unsigned r = checkunsigned(L, 1);
lua_Integer i = luaL_checkinteger(L, 2);
if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))
return b_shift(L, r, -i);
else { /* arithmetic shift for 'negative' number */
if (i >= LUA_NBITS) r = ALLONES;
else
r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */
pushunsigned(L, r);
return 1;
}
}
static int b_rot (lua_State *L, lua_Integer d) {
lua_Unsigned r = checkunsigned(L, 1);
int i = d & (LUA_NBITS - 1); /* i = d % NBITS */
r = trim(r);
if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */
r = (r << i) | (r >> (LUA_NBITS - i));
pushunsigned(L, trim(r));
return 1;
}
static int b_lrot (lua_State *L) {
return b_rot(L, luaL_checkinteger(L, 2));
}
static int b_rrot (lua_State *L) {
return b_rot(L, -luaL_checkinteger(L, 2));
}
/*
** get field and width arguments for field-manipulation functions,
** checking whether they are valid.
** ('luaL_error' called without 'return' to avoid later warnings about
** 'width' being used uninitialized.)
*/
static int fieldargs (lua_State *L, int farg, int *width) {
lua_Integer f = luaL_checkinteger(L, farg);
lua_Integer w = luaL_optinteger(L, farg + 1, 1);
luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
if (f + w > LUA_NBITS)
luaL_error(L, "trying to access non-existent bits");
*width = (int)w;
return (int)f;
}
static int b_extract (lua_State *L) {
int w;
lua_Unsigned r = trim(checkunsigned(L, 1));
int f = fieldargs(L, 2, &w);
r = (r >> f) & mask(w);
pushunsigned(L, r);
return 1;
}
static int b_replace (lua_State *L) {
int w;
lua_Unsigned r = trim(checkunsigned(L, 1));
lua_Unsigned v = trim(checkunsigned(L, 2));
int f = fieldargs(L, 3, &w);
lua_Unsigned m = mask(w);
r = (r & ~(m << f)) | ((v & m) << f);
pushunsigned(L, r);
return 1;
}
static const luaL_Reg bitlib[] = {
{"arshift", b_arshift},
{"band", b_and},
{"bnot", b_not},
{"bor", b_or},
{"bxor", b_xor},
{"btest", b_test},
{"extract", b_extract},
{"lrotate", b_lrot},
{"lshift", b_lshift},
{"replace", b_replace},
{"rrotate", b_rrot},
{"rshift", b_rshift},
{NULL, NULL}
};
LUAMOD_API int luaopen_bit32 (lua_State *L) {
luaL_newlib(L, bitlib);
return 1;
}
#else /* }{ */
LUAMOD_API int luaopen_bit32 (lua_State *L) {
return luaL_error(L, "library 'bit32' has been deprecated");
}
#endif /* } */
| xLua/build/lua-5.3.4/src/lbitlib.c/0 | {
"file_path": "xLua/build/lua-5.3.4/src/lbitlib.c",
"repo_id": "xLua",
"token_count": 2163
} | 2,090 |
/*
** $Id: linit.c,v 1.39 2016/12/04 20:17:24 roberto Exp $
** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
/*
** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit
** it to suit your needs.
**
** You can also *preload* libraries, so that a later 'require' can
** open the library, which is already linked to the application.
** For that, do the following code:
**
** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
** lua_pushcfunction(L, luaopen_modname);
** lua_setfield(L, -2, modname);
** lua_pop(L, 1); // remove PRELOAD table
*/
#include "lprefix.h"
#include <stddef.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/*
** these libs are loaded by lua.c and are readily available to any Lua
** program
*/
static const luaL_Reg loadedlibs[] = {
{"_G", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
#if defined(LUA_COMPAT_BITLIB)
{LUA_BITLIBNAME, luaopen_bit32},
#endif
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
| xLua/build/lua-5.3.4/src/linit.c/0 | {
"file_path": "xLua/build/lua-5.3.4/src/linit.c",
"repo_id": "xLua",
"token_count": 684
} | 2,091 |
/*
** $Id: lprefix.h,v 1.2 2014/12/29 16:54:13 roberto Exp $
** Definitions for Lua code that must come before any other header file
** See Copyright Notice in lua.h
*/
#ifndef lprefix_h
#define lprefix_h
/*
** Allows POSIX/XSI stuff
*/
#if !defined(LUA_USE_C89) /* { */
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#elif _XOPEN_SOURCE == 0
#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */
#endif
/*
** Allows manipulation of large files in gcc and some other compilers
*/
#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
#define _LARGEFILE_SOURCE 1
#define _FILE_OFFSET_BITS 64
#endif
#endif /* } */
/*
** Windows stuff
*/
#if defined(_WIN32) /* { */
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
#endif
#endif /* } */
#endif
| xLua/build/lua-5.3.4/src/lprefix.h/0 | {
"file_path": "xLua/build/lua-5.3.4/src/lprefix.h",
"repo_id": "xLua",
"token_count": 355
} | 2,092 |
/*
** $Id: lualib.h,v 1.45 2017/01/12 17:14:26 roberto Exp $
** Lua standard libraries
** See Copyright Notice in lua.h
*/
#ifndef lualib_h
#define lualib_h
#include "lua.h"
/* version suffix for environment variable names */
#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
LUAMOD_API int (luaopen_base) (lua_State *L);
#define LUA_COLIBNAME "coroutine"
LUAMOD_API int (luaopen_coroutine) (lua_State *L);
#define LUA_TABLIBNAME "table"
LUAMOD_API int (luaopen_table) (lua_State *L);
#define LUA_IOLIBNAME "io"
LUAMOD_API int (luaopen_io) (lua_State *L);
#define LUA_OSLIBNAME "os"
LUAMOD_API int (luaopen_os) (lua_State *L);
#define LUA_STRLIBNAME "string"
LUAMOD_API int (luaopen_string) (lua_State *L);
#define LUA_UTF8LIBNAME "utf8"
LUAMOD_API int (luaopen_utf8) (lua_State *L);
#define LUA_BITLIBNAME "bit32"
LUAMOD_API int (luaopen_bit32) (lua_State *L);
#define LUA_MATHLIBNAME "math"
LUAMOD_API int (luaopen_math) (lua_State *L);
#define LUA_DBLIBNAME "debug"
LUAMOD_API int (luaopen_debug) (lua_State *L);
#define LUA_LOADLIBNAME "package"
LUAMOD_API int (luaopen_package) (lua_State *L);
/* open all previous libraries */
LUALIB_API void (luaL_openlibs) (lua_State *L);
#if !defined(lua_assert)
#define lua_assert(x) ((void)0)
#endif
#endif
| xLua/build/lua-5.3.4/src/lualib.h/0 | {
"file_path": "xLua/build/lua-5.3.4/src/lualib.h",
"repo_id": "xLua",
"token_count": 561
} | 2,093 |
h3 code {
font-family: inherit ;
font-size: inherit ;
}
pre, code {
font-size: 12pt ;
}
span.apii {
color: gray ;
float: right ;
font-family: inherit ;
font-style: normal ;
font-size: small ;
}
h2:before {
content: "" ;
padding-right: 0em ;
}
| xLua/build/lua-5.3.5/doc/manual.css/0 | {
"file_path": "xLua/build/lua-5.3.5/doc/manual.css",
"repo_id": "xLua",
"token_count": 109
} | 2,094 |
/*
** $Id: ldblib.c,v 1.151.1.1 2017/04/19 17:20:42 roberto Exp $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
#define ldblib_c
#define LUA_LIB
#include "lprefix.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** The hook table at registry[&HOOKKEY] maps threads to their current
** hook function. (We only need the unique address of 'HOOKKEY'.)
*/
static const int HOOKKEY = 0;
/*
** If L1 != L, L1 can be in any state, and therefore there are no
** guarantees about its stack space; any push in L1 must be
** checked.
*/
static void checkstack (lua_State *L, lua_State *L1, int n) {
if (L != L1 && !lua_checkstack(L1, n))
luaL_error(L, "stack overflow");
}
static int db_getregistry (lua_State *L) {
lua_pushvalue(L, LUA_REGISTRYINDEX);
return 1;
}
static int db_getmetatable (lua_State *L) {
luaL_checkany(L, 1);
if (!lua_getmetatable(L, 1)) {
lua_pushnil(L); /* no metatable */
}
return 1;
}
static int db_setmetatable (lua_State *L) {
int t = lua_type(L, 2);
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
"nil or table expected");
lua_settop(L, 2);
lua_setmetatable(L, 1);
return 1; /* return 1st argument */
}
static int db_getuservalue (lua_State *L) {
if (lua_type(L, 1) != LUA_TUSERDATA)
lua_pushnil(L);
else
lua_getuservalue(L, 1);
return 1;
}
static int db_setuservalue (lua_State *L) {
luaL_checktype(L, 1, LUA_TUSERDATA);
luaL_checkany(L, 2);
lua_settop(L, 2);
lua_setuservalue(L, 1);
return 1;
}
/*
** Auxiliary function used by several library functions: check for
** an optional thread as function's first argument and set 'arg' with
** 1 if this argument is present (so that functions can skip it to
** access their other arguments)
*/
static lua_State *getthread (lua_State *L, int *arg) {
if (lua_isthread(L, 1)) {
*arg = 1;
return lua_tothread(L, 1);
}
else {
*arg = 0;
return L; /* function will operate over current thread */
}
}
/*
** Variations of 'lua_settable', used by 'db_getinfo' to put results
** from 'lua_getinfo' into result table. Key is always a string;
** value can be a string, an int, or a boolean.
*/
static void settabss (lua_State *L, const char *k, const char *v) {
lua_pushstring(L, v);
lua_setfield(L, -2, k);
}
static void settabsi (lua_State *L, const char *k, int v) {
lua_pushinteger(L, v);
lua_setfield(L, -2, k);
}
static void settabsb (lua_State *L, const char *k, int v) {
lua_pushboolean(L, v);
lua_setfield(L, -2, k);
}
/*
** In function 'db_getinfo', the call to 'lua_getinfo' may push
** results on the stack; later it creates the result table to put
** these objects. Function 'treatstackoption' puts the result from
** 'lua_getinfo' on top of the result table so that it can call
** 'lua_setfield'.
*/
static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
if (L == L1)
lua_rotate(L, -2, 1); /* exchange object and table */
else
lua_xmove(L1, L, 1); /* move object to the "main" stack */
lua_setfield(L, -2, fname); /* put object into table */
}
/*
** Calls 'lua_getinfo' and collects all results in a new table.
** L1 needs stack space for an optional input (function) plus
** two optional outputs (function and line table) from function
** 'lua_getinfo'.
*/
static int db_getinfo (lua_State *L) {
lua_Debug ar;
int arg;
lua_State *L1 = getthread(L, &arg);
const char *options = luaL_optstring(L, arg+2, "flnStu");
checkstack(L, L1, 3);
if (lua_isfunction(L, arg + 1)) { /* info about a function? */
options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
lua_xmove(L, L1, 1);
}
else { /* stack level */
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
lua_pushnil(L); /* level out of range */
return 1;
}
}
if (!lua_getinfo(L1, options, &ar))
return luaL_argerror(L, arg+2, "invalid option");
lua_newtable(L); /* table to collect results */
if (strchr(options, 'S')) {
settabss(L, "source", ar.source);
settabss(L, "short_src", ar.short_src);
settabsi(L, "linedefined", ar.linedefined);
settabsi(L, "lastlinedefined", ar.lastlinedefined);
settabss(L, "what", ar.what);
}
if (strchr(options, 'l'))
settabsi(L, "currentline", ar.currentline);
if (strchr(options, 'u')) {
settabsi(L, "nups", ar.nups);
settabsi(L, "nparams", ar.nparams);
settabsb(L, "isvararg", ar.isvararg);
}
if (strchr(options, 'n')) {
settabss(L, "name", ar.name);
settabss(L, "namewhat", ar.namewhat);
}
if (strchr(options, 't'))
settabsb(L, "istailcall", ar.istailcall);
if (strchr(options, 'L'))
treatstackoption(L, L1, "activelines");
if (strchr(options, 'f'))
treatstackoption(L, L1, "func");
return 1; /* return table */
}
static int db_getlocal (lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
const char *name;
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
if (lua_isfunction(L, arg + 1)) { /* function argument? */
lua_pushvalue(L, arg + 1); /* push function */
lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */
return 1; /* return only name (there is no value) */
}
else { /* stack-level argument */
int level = (int)luaL_checkinteger(L, arg + 1);
if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
checkstack(L, L1, 1);
name = lua_getlocal(L1, &ar, nvar);
if (name) {
lua_xmove(L1, L, 1); /* move local value */
lua_pushstring(L, name); /* push name */
lua_rotate(L, -2, 1); /* re-order */
return 2;
}
else {
lua_pushnil(L); /* no name (nor value) */
return 1;
}
}
}
static int db_setlocal (lua_State *L) {
int arg;
const char *name;
lua_State *L1 = getthread(L, &arg);
lua_Debug ar;
int level = (int)luaL_checkinteger(L, arg + 1);
int nvar = (int)luaL_checkinteger(L, arg + 2);
if (!lua_getstack(L1, level, &ar)) /* out of range? */
return luaL_argerror(L, arg+1, "level out of range");
luaL_checkany(L, arg+3);
lua_settop(L, arg+3);
checkstack(L, L1, 1);
lua_xmove(L, L1, 1);
name = lua_setlocal(L1, &ar, nvar);
if (name == NULL)
lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */
lua_pushstring(L, name);
return 1;
}
/*
** get (if 'get' is true) or set an upvalue from a closure
*/
static int auxupvalue (lua_State *L, int get) {
const char *name;
int n = (int)luaL_checkinteger(L, 2); /* upvalue index */
luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */
name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
if (name == NULL) return 0;
lua_pushstring(L, name);
lua_insert(L, -(get+1)); /* no-op if get is false */
return get + 1;
}
static int db_getupvalue (lua_State *L) {
return auxupvalue(L, 1);
}
static int db_setupvalue (lua_State *L) {
luaL_checkany(L, 3);
return auxupvalue(L, 0);
}
/*
** Check whether a given upvalue from a given closure exists and
** returns its index
*/
static int checkupval (lua_State *L, int argf, int argnup) {
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
"invalid upvalue index");
return nup;
}
static int db_upvalueid (lua_State *L) {
int n = checkupval(L, 1, 2);
lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));
return 1;
}
static int db_upvaluejoin (lua_State *L) {
int n1 = checkupval(L, 1, 2);
int n2 = checkupval(L, 3, 4);
luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
lua_upvaluejoin(L, 1, n1, 3, n2);
return 0;
}
/*
** Call hook function registered at hook table for the current
** thread (if there is one)
*/
static void hookf (lua_State *L, lua_Debug *ar) {
static const char *const hooknames[] =
{"call", "return", "line", "count", "tail call"};
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
lua_pushthread(L);
if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
if (ar->currentline >= 0)
lua_pushinteger(L, ar->currentline); /* push current line */
else lua_pushnil(L);
lua_assert(lua_getinfo(L, "lS", ar));
lua_call(L, 2, 0); /* call hook function */
}
}
/*
** Convert a string mask (for 'sethook') into a bit mask
*/
static int makemask (const char *smask, int count) {
int mask = 0;
if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
if (strchr(smask, 'r')) mask |= LUA_MASKRET;
if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
if (count > 0) mask |= LUA_MASKCOUNT;
return mask;
}
/*
** Convert a bit mask (for 'gethook') into a string mask
*/
static char *unmakemask (int mask, char *smask) {
int i = 0;
if (mask & LUA_MASKCALL) smask[i++] = 'c';
if (mask & LUA_MASKRET) smask[i++] = 'r';
if (mask & LUA_MASKLINE) smask[i++] = 'l';
smask[i] = '\0';
return smask;
}
static int db_sethook (lua_State *L) {
int arg, mask, count;
lua_Hook func;
lua_State *L1 = getthread(L, &arg);
if (lua_isnoneornil(L, arg+1)) { /* no hook? */
lua_settop(L, arg+1);
func = NULL; mask = 0; count = 0; /* turn off hooks */
}
else {
const char *smask = luaL_checkstring(L, arg+2);
luaL_checktype(L, arg+1, LUA_TFUNCTION);
count = (int)luaL_optinteger(L, arg + 3, 0);
func = hookf; mask = makemask(smask, count);
}
if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
lua_createtable(L, 0, 2); /* create a hook table */
lua_pushvalue(L, -1);
lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */
lua_pushstring(L, "k");
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
lua_pushvalue(L, -1);
lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
}
checkstack(L, L1, 1);
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
lua_pushvalue(L, arg + 1); /* value (hook function) */
lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
lua_sethook(L1, func, mask, count);
return 0;
}
static int db_gethook (lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
char buff[5];
int mask = lua_gethookmask(L1);
lua_Hook hook = lua_gethook(L1);
if (hook == NULL) /* no hook? */
lua_pushnil(L);
else if (hook != hookf) /* external hook? */
lua_pushliteral(L, "external hook");
else { /* hook table must exist */
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
checkstack(L, L1, 1);
lua_pushthread(L1); lua_xmove(L1, L, 1);
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
lua_remove(L, -2); /* remove hook table */
}
lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */
lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */
return 3;
}
static int db_debug (lua_State *L) {
for (;;) {
char buffer[250];
lua_writestringerror("%s", "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
strcmp(buffer, "cont\n") == 0)
return 0;
if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
lua_pcall(L, 0, 0, 0))
lua_writestringerror("%s\n", lua_tostring(L, -1));
lua_settop(L, 0); /* remove eventual returns */
}
}
static int db_traceback (lua_State *L) {
int arg;
lua_State *L1 = getthread(L, &arg);
const char *msg = lua_tostring(L, arg + 1);
if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */
lua_pushvalue(L, arg + 1); /* return it untouched */
else {
int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
luaL_traceback(L, L1, msg, level);
}
return 1;
}
static const luaL_Reg dblib[] = {
{"debug", db_debug},
{"getuservalue", db_getuservalue},
{"gethook", db_gethook},
{"getinfo", db_getinfo},
{"getlocal", db_getlocal},
{"getregistry", db_getregistry},
{"getmetatable", db_getmetatable},
{"getupvalue", db_getupvalue},
{"upvaluejoin", db_upvaluejoin},
{"upvalueid", db_upvalueid},
{"setuservalue", db_setuservalue},
{"sethook", db_sethook},
{"setlocal", db_setlocal},
{"setmetatable", db_setmetatable},
{"setupvalue", db_setupvalue},
{"traceback", db_traceback},
{NULL, NULL}
};
LUAMOD_API int luaopen_debug (lua_State *L) {
luaL_newlib(L, dblib);
return 1;
}
| xLua/build/lua-5.3.5/src/ldblib.c/0 | {
"file_path": "xLua/build/lua-5.3.5/src/ldblib.c",
"repo_id": "xLua",
"token_count": 5451
} | 2,095 |
/*
** $Id: lmem.c,v 1.91.1.1 2017/04/19 17:20:42 roberto Exp $
** Interface to Memory Manager
** See Copyright Notice in lua.h
*/
#define lmem_c
#define LUA_CORE
#include "lprefix.h"
#include <stddef.h>
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
/*
** About the realloc function:
** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
** ('osize' is the old size, 'nsize' is the new size)
**
** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
** matter 'x').
**
** * frealloc(ud, p, x, 0) frees the block 'p'
** (in this specific case, frealloc must return NULL);
** particularly, frealloc(ud, NULL, 0, 0) does nothing
** (which is equivalent to free(NULL) in ISO C)
**
** frealloc returns NULL if it cannot create or reallocate the area
** (any reallocation to an equal or smaller size cannot fail!)
*/
#define MINSIZEARRAY 4
void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
int limit, const char *what) {
void *newblock;
int newsize;
if (*size >= limit/2) { /* cannot double it? */
if (*size >= limit) /* cannot grow even a little? */
luaG_runerror(L, "too many %s (limit is %d)", what, limit);
newsize = limit; /* still have at least one free place */
}
else {
newsize = (*size)*2;
if (newsize < MINSIZEARRAY)
newsize = MINSIZEARRAY; /* minimum size */
}
newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
*size = newsize; /* update only when everything else is OK */
return newblock;
}
l_noret luaM_toobig (lua_State *L) {
luaG_runerror(L, "memory allocation error: block too big");
}
/*
** generic allocation routine.
*/
void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
void *newblock;
global_State *g = G(L);
size_t realosize = (block) ? osize : 0;
lua_assert((realosize == 0) == (block == NULL));
#if defined(HARDMEMTESTS)
if (nsize > realosize && g->gcrunning)
luaC_fullgc(L, 1); /* force a GC whenever possible */
#endif
newblock = (*g->frealloc)(g->ud, block, osize, nsize);
if (newblock == NULL && nsize > 0) {
lua_assert(nsize > realosize); /* cannot fail when shrinking a block */
if (g->version) { /* is state fully built? */
luaC_fullgc(L, 1); /* try to free some memory... */
newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
}
if (newblock == NULL)
luaD_throw(L, LUA_ERRMEM);
}
lua_assert((nsize == 0) == (newblock == NULL));
g->GCdebt = (g->GCdebt + nsize) - realosize;
return newblock;
}
| xLua/build/lua-5.3.5/src/lmem.c/0 | {
"file_path": "xLua/build/lua-5.3.5/src/lmem.c",
"repo_id": "xLua",
"token_count": 1065
} | 2,096 |
/*
** $Id: ltable.c,v 2.118.1.4 2018/06/08 16:22:51 roberto Exp $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
#define ltable_c
#define LUA_CORE
#include "lprefix.h"
/*
** Implementation of tables (aka arrays, objects, or hash tables).
** Tables keep its elements in two parts: an array part and a hash part.
** Non-negative integer keys are all candidates to be kept in the array
** part. The actual size of the array is the largest 'n' such that
** more than half the slots between 1 and n are in use.
** Hash uses a mix of chained scatter table with Brent's variation.
** A main invariant of these tables is that, if an element is not
** in its main position (i.e. the 'original' position that its hash gives
** to it), then the colliding element is in its own main position.
** Hence even when the load factor reaches 100%, performance remains good.
*/
#include <math.h>
#include <limits.h>
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lvm.h"
/*
** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is
** the largest integer such that MAXASIZE fits in an unsigned int.
*/
#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
#define MAXASIZE (1u << MAXABITS)
/*
** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest
** integer such that 2^MAXHBITS fits in a signed int. (Note that the
** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still
** fits comfortably in an unsigned int.)
*/
#define MAXHBITS (MAXABITS - 1)
#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
#define hashstr(t,str) hashpow2(t, (str)->hash)
#define hashboolean(t,p) hashpow2(t, p)
#define hashint(t,i) hashpow2(t, i)
/*
** for some types, it is better to avoid modulus by power of 2, as
** they tend to have many 2 factors.
*/
#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
#define hashpointer(t,p) hashmod(t, point2uint(p))
#define dummynode (&dummynode_)
static const Node dummynode_ = {
{NILCONSTANT}, /* value */
{{NILCONSTANT, 0}} /* key */
};
/*
** Hash for floating-point numbers.
** The main computation should be just
** n = frexp(n, &i); return (n * INT_MAX) + i
** but there are some numerical subtleties.
** In a two-complement representation, INT_MAX does not has an exact
** representation as a float, but INT_MIN does; because the absolute
** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
** INT_MIN.
*/
#if !defined(l_hashfloat)
static int l_hashfloat (lua_Number n) {
int i;
lua_Integer ni;
n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
return 0;
}
else { /* normal case */
unsigned int u = cast(unsigned int, i) + cast(unsigned int, ni);
return cast_int(u <= cast(unsigned int, INT_MAX) ? u : ~u);
}
}
#endif
/*
** returns the 'main' position of an element in a table (that is, the index
** of its hash value)
*/
static Node *mainposition (const Table *t, const TValue *key) {
switch (ttype(key)) {
case LUA_TNUMINT:
return hashint(t, ivalue(key));
case LUA_TNUMFLT:
return hashmod(t, l_hashfloat(fltvalue(key)));
case LUA_TSHRSTR:
return hashstr(t, tsvalue(key));
case LUA_TLNGSTR:
return hashpow2(t, luaS_hashlongstr(tsvalue(key)));
case LUA_TBOOLEAN:
return hashboolean(t, bvalue(key));
case LUA_TLIGHTUSERDATA:
return hashpointer(t, pvalue(key));
case LUA_TLCF:
return hashpointer(t, fvalue(key));
default:
lua_assert(!ttisdeadkey(key));
return hashpointer(t, gcvalue(key));
}
}
/*
** returns the index for 'key' if 'key' is an appropriate key to live in
** the array part of the table, 0 otherwise.
*/
static unsigned int arrayindex (const TValue *key) {
if (ttisinteger(key)) {
lua_Integer k = ivalue(key);
if (0 < k && (lua_Unsigned)k <= MAXASIZE)
return cast(unsigned int, k); /* 'key' is an appropriate array index */
}
return 0; /* 'key' did not match some condition */
}
/*
** returns the index of a 'key' for table traversals. First goes all
** elements in the array part, then elements in the hash part. The
** beginning of a traversal is signaled by 0.
*/
static unsigned int findindex (lua_State *L, Table *t, StkId key) {
unsigned int i;
if (ttisnil(key)) return 0; /* first iteration */
i = arrayindex(key);
if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */
return i; /* yes; that's the index */
else {
int nx;
Node *n = mainposition(t, key);
for (;;) { /* check whether 'key' is somewhere in the chain */
/* key may be dead already, but it is ok to use it in 'next' */
if (luaV_rawequalobj(gkey(n), key) ||
(ttisdeadkey(gkey(n)) && iscollectable(key) &&
deadvalue(gkey(n)) == gcvalue(key))) {
i = cast_int(n - gnode(t, 0)); /* key index in hash table */
/* hash elements are numbered after array ones */
return (i + 1) + t->sizearray;
}
nx = gnext(n);
if (nx == 0)
luaG_runerror(L, "invalid key to 'next'"); /* key not found */
else n += nx;
}
}
}
int luaH_next (lua_State *L, Table *t, StkId key) {
unsigned int i = findindex(L, t, key); /* find original element */
for (; i < t->sizearray; i++) { /* try first array part */
if (!ttisnil(&t->array[i])) { /* a non-nil value? */
setivalue(key, i + 1);
setobj2s(L, key+1, &t->array[i]);
return 1;
}
}
for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */
if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
setobj2s(L, key, gkey(gnode(t, i)));
setobj2s(L, key+1, gval(gnode(t, i)));
return 1;
}
}
return 0; /* no more elements */
}
/*
** {=============================================================
** Rehash
** ==============================================================
*/
/*
** Compute the optimal size for the array part of table 't'. 'nums' is a
** "count array" where 'nums[i]' is the number of integers in the table
** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
** integer keys in the table and leaves with the number of keys that
** will go to the array part; return the optimal size.
*/
static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
int i;
unsigned int twotoi; /* 2^i (candidate for optimal size) */
unsigned int a = 0; /* number of elements smaller than 2^i */
unsigned int na = 0; /* number of elements to go to array part */
unsigned int optimal = 0; /* optimal size for array part */
/* loop while keys can fill more than half of total size */
for (i = 0, twotoi = 1;
twotoi > 0 && *pna > twotoi / 2;
i++, twotoi *= 2) {
if (nums[i] > 0) {
a += nums[i];
if (a > twotoi/2) { /* more than half elements present? */
optimal = twotoi; /* optimal size (till now) */
na = a; /* all elements up to 'optimal' will go to array part */
}
}
}
lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
*pna = na;
return optimal;
}
static int countint (const TValue *key, unsigned int *nums) {
unsigned int k = arrayindex(key);
if (k != 0) { /* is 'key' an appropriate array index? */
nums[luaO_ceillog2(k)]++; /* count as such */
return 1;
}
else
return 0;
}
/*
** Count keys in array part of table 't': Fill 'nums[i]' with
** number of keys that will go into corresponding slice and return
** total number of non-nil keys.
*/
static unsigned int numusearray (const Table *t, unsigned int *nums) {
int lg;
unsigned int ttlg; /* 2^lg */
unsigned int ause = 0; /* summation of 'nums' */
unsigned int i = 1; /* count to traverse all array keys */
/* traverse each slice */
for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
unsigned int lc = 0; /* counter */
unsigned int lim = ttlg;
if (lim > t->sizearray) {
lim = t->sizearray; /* adjust upper limit */
if (i > lim)
break; /* no more elements to count */
}
/* count elements in range (2^(lg - 1), 2^lg] */
for (; i <= lim; i++) {
if (!ttisnil(&t->array[i-1]))
lc++;
}
nums[lg] += lc;
ause += lc;
}
return ause;
}
static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
int totaluse = 0; /* total number of elements */
int ause = 0; /* elements added to 'nums' (can go to array part) */
int i = sizenode(t);
while (i--) {
Node *n = &t->node[i];
if (!ttisnil(gval(n))) {
ause += countint(gkey(n), nums);
totaluse++;
}
}
*pna += ause;
return totaluse;
}
static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
unsigned int i;
luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
for (i=t->sizearray; i<size; i++)
setnilvalue(&t->array[i]);
t->sizearray = size;
}
static void setnodevector (lua_State *L, Table *t, unsigned int size) {
if (size == 0) { /* no elements to hash part? */
t->node = cast(Node *, dummynode); /* use common 'dummynode' */
t->lsizenode = 0;
t->lastfree = NULL; /* signal that it is using dummy node */
}
else {
int i;
int lsize = luaO_ceillog2(size);
if (lsize > MAXHBITS)
luaG_runerror(L, "table overflow");
size = twoto(lsize);
t->node = luaM_newvector(L, size, Node);
for (i = 0; i < (int)size; i++) {
Node *n = gnode(t, i);
gnext(n) = 0;
setnilvalue(wgkey(n));
setnilvalue(gval(n));
}
t->lsizenode = cast_byte(lsize);
t->lastfree = gnode(t, size); /* all positions are free */
}
}
typedef struct {
Table *t;
unsigned int nhsize;
} AuxsetnodeT;
static void auxsetnode (lua_State *L, void *ud) {
AuxsetnodeT *asn = cast(AuxsetnodeT *, ud);
setnodevector(L, asn->t, asn->nhsize);
}
void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
unsigned int nhsize) {
unsigned int i;
int j;
AuxsetnodeT asn;
unsigned int oldasize = t->sizearray;
int oldhsize = allocsizenode(t);
Node *nold = t->node; /* save old hash ... */
if (nasize > oldasize) /* array part must grow? */
setarrayvector(L, t, nasize);
/* create new hash part with appropriate size */
asn.t = t; asn.nhsize = nhsize;
if (luaD_rawrunprotected(L, auxsetnode, &asn) != LUA_OK) { /* mem. error? */
setarrayvector(L, t, oldasize); /* array back to its original size */
luaD_throw(L, LUA_ERRMEM); /* rethrow memory error */
}
if (nasize < oldasize) { /* array part must shrink? */
t->sizearray = nasize;
/* re-insert elements from vanishing slice */
for (i=nasize; i<oldasize; i++) {
if (!ttisnil(&t->array[i]))
luaH_setint(L, t, i + 1, &t->array[i]);
}
/* shrink array */
luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
}
/* re-insert elements from hash part */
for (j = oldhsize - 1; j >= 0; j--) {
Node *old = nold + j;
if (!ttisnil(gval(old))) {
/* doesn't need barrier/invalidate cache, as entry was
already present in the table */
setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));
}
}
if (oldhsize > 0) /* not the dummy node? */
luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */
}
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
int nsize = allocsizenode(t);
luaH_resize(L, t, nasize, nsize);
}
/*
** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
*/
static void rehash (lua_State *L, Table *t, const TValue *ek) {
unsigned int asize; /* optimal size for array part */
unsigned int na; /* number of keys in the array part */
unsigned int nums[MAXABITS + 1];
int i;
int totaluse;
for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
na = numusearray(t, nums); /* count keys in array part */
totaluse = na; /* all those keys are integer keys */
totaluse += numusehash(t, nums, &na); /* count keys in hash part */
/* count extra key */
na += countint(ek, nums);
totaluse++;
/* compute new size for array part */
asize = computesizes(nums, &na);
/* resize the table to new computed sizes */
luaH_resize(L, t, asize, totaluse - na);
}
/*
** }=============================================================
*/
Table *luaH_new (lua_State *L) {
GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
Table *t = gco2t(o);
t->metatable = NULL;
t->flags = cast_byte(~0);
t->array = NULL;
t->sizearray = 0;
setnodevector(L, t, 0);
return t;
}
void luaH_free (lua_State *L, Table *t) {
if (!isdummy(t))
luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
luaM_freearray(L, t->array, t->sizearray);
luaM_free(L, t);
}
static Node *getfreepos (Table *t) {
if (!isdummy(t)) {
while (t->lastfree > t->node) {
t->lastfree--;
if (ttisnil(gkey(t->lastfree)))
return t->lastfree;
}
}
return NULL; /* could not find a free place */
}
/*
** inserts a new key into a hash table; first, check whether key's main
** position is free. If not, check whether colliding node is in its main
** position or not: if it is not, move colliding node to an empty place and
** put new key in its main position; otherwise (colliding node is in its main
** position), new key goes to an empty position.
*/
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
TValue aux;
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
else if (ttisfloat(key)) {
lua_Integer k;
if (luaV_tointeger(key, &k, 0)) { /* does index fit in an integer? */
setivalue(&aux, k);
key = &aux; /* insert it as an integer */
}
else if (luai_numisnan(fltvalue(key)))
luaG_runerror(L, "table index is NaN");
}
mp = mainposition(t, key);
if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */
Node *othern;
Node *f = getfreepos(t); /* get a free place */
if (f == NULL) { /* cannot find a free place? */
rehash(L, t, key); /* grow table */
/* whatever called 'newkey' takes care of TM cache */
return luaH_set(L, t, key); /* insert key into grown table */
}
lua_assert(!isdummy(t));
othern = mainposition(t, gkey(mp));
if (othern != mp) { /* is colliding node out of its main position? */
/* yes; move colliding node into free position */
while (othern + gnext(othern) != mp) /* find previous */
othern += gnext(othern);
gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
*f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
if (gnext(mp) != 0) {
gnext(f) += cast_int(mp - f); /* correct 'next' */
gnext(mp) = 0; /* now 'mp' is free */
}
setnilvalue(gval(mp));
}
else { /* colliding node is in its own main position */
/* new node will go into free position */
if (gnext(mp) != 0)
gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
else lua_assert(gnext(f) == 0);
gnext(mp) = cast_int(f - mp);
mp = f;
}
}
setnodekey(L, &mp->i_key, key);
luaC_barrierback(L, t, key);
lua_assert(ttisnil(gval(mp)));
return gval(mp);
}
/*
** search function for integers
*/
const TValue *luaH_getint (Table *t, lua_Integer key) {
/* (1 <= key && key <= t->sizearray) */
if (l_castS2U(key) - 1 < t->sizearray)
return &t->array[key - 1];
else {
Node *n = hashint(t, key);
for (;;) { /* check whether 'key' is somewhere in the chain */
if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key)
return gval(n); /* that's it */
else {
int nx = gnext(n);
if (nx == 0) break;
n += nx;
}
}
return luaO_nilobject;
}
}
/*
** search function for short strings
*/
const TValue *luaH_getshortstr (Table *t, TString *key) {
Node *n = hashstr(t, key);
lua_assert(key->tt == LUA_TSHRSTR);
for (;;) { /* check whether 'key' is somewhere in the chain */
const TValue *k = gkey(n);
if (ttisshrstring(k) && eqshrstr(tsvalue(k), key))
return gval(n); /* that's it */
else {
int nx = gnext(n);
if (nx == 0)
return luaO_nilobject; /* not found */
n += nx;
}
}
}
/*
** "Generic" get version. (Not that generic: not valid for integers,
** which may be in array part, nor for floats with integral values.)
*/
static const TValue *getgeneric (Table *t, const TValue *key) {
Node *n = mainposition(t, key);
for (;;) { /* check whether 'key' is somewhere in the chain */
if (luaV_rawequalobj(gkey(n), key))
return gval(n); /* that's it */
else {
int nx = gnext(n);
if (nx == 0)
return luaO_nilobject; /* not found */
n += nx;
}
}
}
const TValue *luaH_getstr (Table *t, TString *key) {
if (key->tt == LUA_TSHRSTR)
return luaH_getshortstr(t, key);
else { /* for long strings, use generic case */
TValue ko;
setsvalue(cast(lua_State *, NULL), &ko, key);
return getgeneric(t, &ko);
}
}
/*
** main search function
*/
const TValue *luaH_get (Table *t, const TValue *key) {
switch (ttype(key)) {
case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
case LUA_TNIL: return luaO_nilobject;
case LUA_TNUMFLT: {
lua_Integer k;
if (luaV_tointeger(key, &k, 0)) /* index is int? */
return luaH_getint(t, k); /* use specialized version */
/* else... */
} /* FALLTHROUGH */
default:
return getgeneric(t, key);
}
}
/*
** beware: when using this function you probably need to check a GC
** barrier and invalidate the TM cache.
*/
TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
const TValue *p = luaH_get(t, key);
if (p != luaO_nilobject)
return cast(TValue *, p);
else return luaH_newkey(L, t, key);
}
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
const TValue *p = luaH_getint(t, key);
TValue *cell;
if (p != luaO_nilobject)
cell = cast(TValue *, p);
else {
TValue k;
setivalue(&k, key);
cell = luaH_newkey(L, t, &k);
}
setobj2t(L, cell, value);
}
static lua_Unsigned unbound_search (Table *t, lua_Unsigned j) {
lua_Unsigned i = j; /* i is zero or a present index */
j++;
/* find 'i' and 'j' such that i is present and j is not */
while (!ttisnil(luaH_getint(t, j))) {
i = j;
if (j > l_castS2U(LUA_MAXINTEGER) / 2) { /* overflow? */
/* table was built with bad purposes: resort to linear search */
i = 1;
while (!ttisnil(luaH_getint(t, i))) i++;
return i - 1;
}
j *= 2;
}
/* now do a binary search between them */
while (j - i > 1) {
lua_Unsigned m = (i+j)/2;
if (ttisnil(luaH_getint(t, m))) j = m;
else i = m;
}
return i;
}
/*
** Try to find a boundary in table 't'. A 'boundary' is an integer index
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
*/
lua_Unsigned luaH_getn (Table *t) {
unsigned int j = t->sizearray;
if (j > 0 && ttisnil(&t->array[j - 1])) {
/* there is a boundary in the array part: (binary) search for it */
unsigned int i = 0;
while (j - i > 1) {
unsigned int m = (i+j)/2;
if (ttisnil(&t->array[m - 1])) j = m;
else i = m;
}
return i;
}
/* else must find a boundary in hash part */
else if (isdummy(t)) /* hash part is empty? */
return j; /* that is easy... */
else return unbound_search(t, j);
}
#if defined(LUA_DEBUG)
Node *luaH_mainposition (const Table *t, const TValue *key) {
return mainposition(t, key);
}
int luaH_isdummy (const Table *t) { return isdummy(t); }
#endif
| xLua/build/lua-5.3.5/src/ltable.c/0 | {
"file_path": "xLua/build/lua-5.3.5/src/ltable.c",
"repo_id": "xLua",
"token_count": 8303
} | 2,097 |
/*
** $Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp $
** Buffered streams
** See Copyright Notice in lua.h
*/
#define lzio_c
#define LUA_CORE
#include "lprefix.h"
#include <string.h>
#include "lua.h"
#include "llimits.h"
#include "lmem.h"
#include "lstate.h"
#include "lzio.h"
int luaZ_fill (ZIO *z) {
size_t size;
lua_State *L = z->L;
const char *buff;
lua_unlock(L);
buff = z->reader(L, z->data, &size);
lua_lock(L);
if (buff == NULL || size == 0)
return EOZ;
z->n = size - 1; /* discount char being returned */
z->p = buff;
return cast_uchar(*(z->p++));
}
void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
z->L = L;
z->reader = reader;
z->data = data;
z->n = 0;
z->p = NULL;
}
/* --------------------------------------------------------------- read --- */
size_t luaZ_read (ZIO *z, void *b, size_t n) {
while (n) {
size_t m;
if (z->n == 0) { /* no bytes in buffer? */
if (luaZ_fill(z) == EOZ) /* try to read more */
return n; /* no more input; return number of missing bytes */
else {
z->n++; /* luaZ_fill consumed first byte; put it back */
z->p--;
}
}
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
memcpy(b, z->p, m);
z->n -= m;
z->p += m;
b = (char *)b + m;
n -= m;
}
return 0;
}
| xLua/build/lua-5.3.5/src/lzio.c/0 | {
"file_path": "xLua/build/lua-5.3.5/src/lzio.c",
"repo_id": "xLua",
"token_count": 628
} | 2,098 |
/*
** $Id: lapi.h $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
#ifndef lapi_h
#define lapi_h
#include "llimits.h"
#include "lstate.h"
/* Increments 'L->top', checking for stack overflows */
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
"stack overflow");}
/*
** If a call returns too many multiple returns, the callee may not have
** stack space to accommodate all results. In this case, this macro
** increases its stack space ('L->ci->top').
*/
#define adjustresults(L,nres) \
{ if ((nres) <= LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
/* Ensure the stack has at least 'n' elements */
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
"not enough elements in the stack")
/*
** To reduce the overhead of returning from C functions, the presence of
** to-be-closed variables in these functions is coded in the CallInfo's
** field 'nresults', in a way that functions with no to-be-closed variables
** with zero, one, or "all" wanted results have no overhead. Functions
** with other number of wanted results, as well as functions with
** variables to be closed, have an extra check.
*/
#define hastocloseCfunc(n) ((n) < LUA_MULTRET)
#define codeNresults(n) (-(n) - 3)
#endif
| xLua/build/lua-5.4.1/src/lapi.h/0 | {
"file_path": "xLua/build/lua-5.4.1/src/lapi.h",
"repo_id": "xLua",
"token_count": 445
} | 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.